目录
# 1,protobuf定义的类与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); //赋值