当前位置:首页 > 文章列表 > Golang > Go问答 > 将 C++ 字节结构转换/解析为 Go

将 C++ 字节结构转换/解析为 Go

来源:stackoverflow 2024-04-13 15:51:34 0浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《将 C++ 字节结构转换/解析为 Go》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在用go读取一些数据包,其中的字段是c++数据类型。我尝试解析数据,但读取的是垃圾值。

这是一个小例子 - c++ 中特定数据类型的数据规格表如下,

struct cartelemetrydata
{
    uint16    m_speed;                      
    uint8     m_throttle;                   
    int8      m_steer;                      
    uint8     m_brake;                     
    uint8     m_clutch;                     
    int8      m_gear;                       
    uint16    m_enginerpm;                  
    uint8     m_drs;                        
    uint8     m_revlightspercent;           
    uint16    m_brakestemperature[4];       
    uint16    m_tyressurfacetemperature[4]; 
    uint16    m_tyresinnertemperature[4];   
    uint16    m_enginetemperature;          
    float     m_tyrespressure[4];           
};

下面是我在 go 中定义的内容

type cartelemetrydata struct {
    speed                   uint16
    throttle                uint8
    steer                   int8
    brake                   uint8
    clutch                  uint8
    gear                    int8
    enginerpm               uint16
    drs                     uint8
    revlightspercent        uint8
    brakestemperature       [4]uint16
    tyressurfacetemperature [4]uint16
    tyresinnertemperature   [4]uint16
    enginetemperature       uint16
    tyrespressure           [4]float32
}

对于实际的解组,我正在这样做 -

func decodePayload(dataStruct interface{}, payload []byte) {
    dataReader := bytes.NewReader(payload[:])
    binary.Read(dataReader, binary.LittleEndian, dataStruct)
}

payload := make([]byte, 2048)
s.conn.ReadFromUDP(payload[:])
telemetryData := &data.CarTelemetryData{}
s.PacketsRcvd += 1
decodePayload(telemetryData, payload)

我怀疑这是因为数据类型不相等,并且在将字节读入 go 数据类型时存在一些转换问题,而它们最初是作为 c++ 打包的。我该如何处理这个问题?

注意:我对发送的数据没有任何控制权,这是由第三方服务发送的。


正确答案


您面临的问题与结构成员的对齐有关。您可以阅读更多相关内容 here,但简而言之,c++ 编译器有时会添加填充字节,以保持架构所期望的自然对齐。如果不使用这种对齐方式,可能会导致性能下降甚至访问冲突。

例如,对于 x86/x64,大多数类型的对齐方式通常(但不一定保证)与大小相同。我们可以看到

#include 
#include 

std::size_t offsets[] = {
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v<__uint128_t>,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v<__int128_t>,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
    std::alignment_of_v,
};

编译为

offsets:
        .quad   1
        .quad   2
        .quad   4
        .quad   8
        .quad   16
        .quad   1
        .quad   2
        .quad   4
        .quad   8
        .quad   16
        .quad   4
        .quad   8
        .quad   16
        .quad   8

由于这些(和其他)实现细节,建议不要依赖内部表示。然而,在某些情况下,其他方法可能不够快(例如逐个字段序列化),或者您可能无法更改 c++ 代码,例如 op。

binary.Read 需要打包数据,但 c++ 将使用填充。我们需要使用依赖于编译器的指令,例如 #pragma pack(1) 或添加填充 go 结构。第一个选项不适用于 op,因此我们将使用第二个。

我们可以使用 offsetof 宏来确定结构体成员相对于结构体本身的偏移量。我们可以做类似的事情

#include 
#include 
#include 

using int8 = std::int8_t;
using uint8 = std::uint8_t;
using uint16 = std::uint16_t;

struct cartelemetrydata {
    uint16 m_speed;
    uint8 m_throttle;
    int8 m_steer;
    uint8 m_brake;
    uint8 m_clutch;
    int8 m_gear;
    uint16 m_enginerpm;
    uint8 m_drs;
    uint8 m_revlightspercent;
    uint16 m_brakestemperature[4];
    uint16 m_tyressurfacetemperature[4];
    uint16 m_tyresinnertemperature[4];
    uint16 m_enginetemperature;
    float m_tyrespressure[4];
};

// c++ has no reflection (yet) so we need to list every member
constexpr auto offsets = std::array{
    offsetof(cartelemetrydata, m_speed),
    offsetof(cartelemetrydata, m_throttle),
    offsetof(cartelemetrydata, m_steer),
    offsetof(cartelemetrydata, m_brake),
    offsetof(cartelemetrydata, m_clutch),
    offsetof(cartelemetrydata, m_gear),
    offsetof(cartelemetrydata, m_enginerpm),
    offsetof(cartelemetrydata, m_drs),
    offsetof(cartelemetrydata, m_revlightspercent),
    offsetof(cartelemetrydata, m_brakestemperature),
    offsetof(cartelemetrydata, m_tyressurfacetemperature),
    offsetof(cartelemetrydata, m_tyresinnertemperature),
    offsetof(cartelemetrydata, m_enginetemperature),
    offsetof(cartelemetrydata, m_tyrespressure),
};

constexpr auto sizes = std::array{
    sizeof(cartelemetrydata::m_speed),
    sizeof(cartelemetrydata::m_throttle),
    sizeof(cartelemetrydata::m_steer),
    sizeof(cartelemetrydata::m_brake),
    sizeof(cartelemetrydata::m_clutch),
    sizeof(cartelemetrydata::m_gear),
    sizeof(cartelemetrydata::m_enginerpm),
    sizeof(cartelemetrydata::m_drs),
    sizeof(cartelemetrydata::m_revlightspercent),
    sizeof(cartelemetrydata::m_brakestemperature),
    sizeof(cartelemetrydata::m_tyressurfacetemperature),
    sizeof(cartelemetrydata::m_tyresinnertemperature),
    sizeof(cartelemetrydata::m_enginetemperature),
    sizeof(cartelemetrydata::m_tyrespressure),
};

constexpr auto computepadding() {
    std::array result;

    std::size_t expectedoffset = 0;

    for (std::size_t i = 0; i < offsets.size(); i++) {
        result.at(i) = offsets.at(i) - expectedoffset;
        expectedoffset = offsets.at(i) + sizes.at(i);
    }

    return result;
}

auto padding = computepadding();

编译为 (constexpr ftw)

padding:
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   1
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   0
        .quad   2

因此,在 x86 上,我们需要在 enginerpm 之前有一个字节,在 tyrespressure 之前需要两个字节。

所以,let's check if that works

c++:

#include 
#include 
#include 
#include 
#include 

using int8 = std::int8_t;
using uint8 = std::uint8_t;
using uint16 = std::uint16_t;

struct cartelemetrydata {
    uint16 m_speed;
    uint8 m_throttle;
    int8 m_steer;
    uint8 m_brake;
    uint8 m_clutch;
    int8 m_gear;
    uint16 m_enginerpm;
    uint8 m_drs;
    uint8 m_revlightspercent;
    uint16 m_brakestemperature[4];
    uint16 m_tyressurfacetemperature[4];
    uint16 m_tyresinnertemperature[4];
    uint16 m_enginetemperature;
    float m_tyrespressure[4];
};

int main() {
    cartelemetrydata data = {
        .m_speed = 1,
        .m_throttle = 2,
        .m_steer = 3,
        .m_brake = 4,
        .m_clutch = 5,
        .m_gear = 6,
        .m_enginerpm = 7,
        .m_drs = 8,
        .m_revlightspercent = 9,
        .m_brakestemperature = {10, 11, 12, 13},
        .m_tyressurfacetemperature = {14, 15, 16, 17},
        .m_tyresinnertemperature = {18, 19, 20, 21},
        .m_enginetemperature = 22,
        .m_tyrespressure = {23, 24, 25, 26},
    };

    std::cout << "b := []byte{" << std::hex << std::setfill('0');

    for (auto byte : std::as_bytes(std::span(&data, 1))) {
        std::cout << "0x" << std::setw(2) << static_cast(byte)
                  << ", ";
    }

    std::cout << "}";
}

结果

b := []byte{0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x07, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e, 0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13, 0x00, 0x14, 0x00, 0x15, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x41, 0x00, 0x00, 0xc0, 0x41, 0x00, 0x00, 0xc8, 0x41, 0x00, 0x00, 0xd0, 0x41, }

让我们在 go 中使用它:

// type your code here, or load an example.
// your function name should start with a capital letter.
package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type cartelemetrydata struct {
    speed                   uint16
    throttle                uint8
    steer                   int8
    brake                   uint8
    clutch                  uint8
    gear                    int8
    _                       uint8
    enginerpm               uint16
    drs                     uint8
    revlightspercent        uint8
    brakestemperature       [4]uint16
    tyressurfacetemperature [4]uint16
    tyresinnertemperature   [4]uint16
    enginetemperature       uint16
    _                       uint16
    tyrespressure           [4]float32
}

func main() {
    b := []byte{0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x07, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e, 0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13, 0x00, 0x14, 0x00, 0x15, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x41, 0x00, 0x00, 0xc0, 0x41, 0x00, 0x00, 0xc8, 0x41, 0x00, 0x00, 0xd0, 0x41}

    var datastruct cartelemetrydata

    datareader := bytes.newreader(b[:])
    binary.read(datareader, binary.littleendian, &datastruct)

    fmt.printf("%+v", datastruct)
}

打印内容

{Speed:1 Throttle:2 Steer:3 Brake:4 Clutch:5 Gear:6 _:0 EngineRPM:7 DRS:8 RevLightsPercent:9 BrakesTemperature:[10 11 12 13] TyresSurfaceTemperature:[14 15 16 17] TyresInnerTemperature:[18 19 20 21] EngineTemperature:22 _:0 TyresPressure:[23 24 25 26]}

取出填充字节,结果失败。

好了,本文到此结束,带大家了解了《将 C++ 字节结构转换/解析为 Go》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
golang 生成的 WebAssembly 上的 Websocket?golang 生成的 WebAssembly 上的 Websocket?
上一篇
golang 生成的 WebAssembly 上的 Websocket?
Java内存管理中的根集搜索算法有哪些?
下一篇
Java内存管理中的根集搜索算法有哪些?
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    2次使用
  • Brev AI:零注册门槛的全功能免费AI音乐创作平台
    Brev AI
    探索Brev AI,一个无需注册即可免费使用的AI音乐创作平台,提供多功能工具如音乐生成、去人声、歌词创作等,适用于内容创作、商业配乐和个人创作,满足您的音乐需求。
    2次使用
  • AI音乐实验室:一站式AI音乐创作平台,助力音乐创作
    AI音乐实验室
    AI音乐实验室(https://www.aimusiclab.cn/)是一款专注于AI音乐创作的平台,提供从作曲到分轨的全流程工具,降低音乐创作门槛。免费与付费结合,适用于音乐爱好者、独立音乐人及内容创作者,助力提升创作效率。
    2次使用
  • SEO标题PixPro:AI驱动网页端图像处理平台,提升效率的终极解决方案
    PixPro
    SEO摘要PixPro是一款专注于网页端AI图像处理的平台,提供高效、多功能的图像处理解决方案。通过AI擦除、扩图、抠图、裁切和压缩等功能,PixPro帮助开发者和企业实现“上传即处理”的智能化升级,适用于电商、社交媒体等高频图像处理场景。了解更多PixPro的核心功能和应用案例,提升您的图像处理效率。
    2次使用
  • EasyMusic.ai:零门槛AI音乐生成平台,专业级输出助力全场景创作
    EasyMusic
    EasyMusic.ai是一款面向全场景音乐创作需求的AI音乐生成平台,提供“零门槛创作 专业级输出”的服务。无论你是内容创作者、音乐人、游戏开发者还是教育工作者,都能通过EasyMusic.ai快速生成高品质音乐,满足短视频、游戏、广告、教育等多元需求。平台支持一键生成与深度定制,积累了超10万创作者,生成超100万首音乐作品,用户满意度达99%。
    3次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码