Protobuf学习笔记(二)proto类与vector,数组的相互转换

26 篇文章 1 订阅
21 篇文章 2 订阅

目录

# 1,protobuf定义的类与std::vector的相互转换。 

# 2,protobuf定义的类与数组的相互转换。

# 3,std::vector与数组的相互转换。


# 1,protobuf定义的类与std::vector的相互转换。 

①使用protobuf定义结构化的类,这里不做描述,可参考上一篇。

②protobuf定义的类 转 std::vector。

CanBasicInfo st_can_basicinfo;    //实例化protobuf定义的类

st_can_basicinfo.set_socdsp(11);    //给类中的对象(信号)赋值【只对其中一个举例】

int len = st_can_basicinfo.ByteSizeLong();    //获取类的大小

std::vector<uint8_t> buf(len);    //定义一个std::vector的buf

st_can_basicinfo.SerializeToArray(buf.data(),buf.size());    //序列化,将protobuf定义的类序列化为std::vector类型

pub->Publish(buf.data(), buf.size());    //将序列化后的数据发布出去

③std::vector 转 protobuf定义的类。

获取到的数据类型是    std::shared_ptr<std::vector<uint8_t>>& data

CanBasicInfo st_can_basicinfo;    //实例化protobuf定义的类。

st_can_basicinfo.ParseFromArray(data->data(),data->size());    //反序列化,将std::vector的指针类型,转换为 protobuf定义的类。

【注:如果不是std::vector的指针类型,是std::vector 类型 反序列化也是类似的】

signal = st_can_basicinfo.socdsp();//获取类中的对象。

# 2,protobuf定义的类与数组的相互转换。

④protobuf定义的类 转 数组。

CanBasicInfo st_can_basicinfo;    //实例化protobuf定义的类

st_can_basicinfo.set_socdsp(11);    //给类中的对象(信号)赋值【只对其中一个举例】

int len = st_can_basicinfo.ByteSizeLong();    //获取类的大小

uint8_t buf[512];    //定义一个数组

st_can_basicinfo.SerializeToArray(buf,len);

⑤数组 转 protobuf定义的类。

获取之前的buf数组与len;

CanBasicInfo st_can_basicinfo;    //实例化protobuf定义的类。

st_can_basicinfo.ParseFromArray(buf,len);    //反序列化,将buf数组,转换为 protobuf定义的类。

signal = st_can_basicinfo.socdsp();//获取类中的对象。

# 3,std::vector与数组的相互转换。

⑥std::vector 转 数组。

std::vector<uint8_t> vector_data;    //定义std::vector

uint8_t buf[512];    //定义数组

int len = 512;    //定义长度

memcpy(buf,&vector_data[0],vector_data.size()*sizeof(vector_data[0]));    //内存拷贝

如果转部分:(从vector_data[6]开始,长度为4)memcpy(buf,&vector_data[6],4);

⑦数组 转 std::vector

std::vector<uint8_t> vector_data;    //定义std::vector

uint8_t buf[512];    //定义数组

int len = 512;    //定义长度

data.assign(buf,buf+len);    //赋值

 

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值