Protobuf C++ serialize到char*,便于在网络传输

看到这篇文章 https://blog.csdn.net/mycwq/article/details/19619875
作者的原因:在以上例子中,protobuf 序列化的 string 数据里含有 ‘\0’ 字符。如果以 char* 取protobuf序列化后的数据,将会丢失部分数据。
看到下面的回复中:

手册里也说了。string只是当成容器用。里面放的还是二进制数据。bool SerializeToString(string* output) const;: serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string class as a convenient container

把这篇博客中的代码运行了一遍,结果如下:
这里写图片描述
在网络中,我们经常传输的是char*类型的字符数组,于是:

int size = person.ByteSize();
void *buffer = malloc(size);
person.SerializeToArray(buffer, size);

string str3;
str3.assign((char*)buffer, size);

tutorial::Person person3;
bool ret3 = person3.ParseFromString(str3);

这样做是可以反序列化出来的。
先记录一下使用protobuf C++版遇到的问题,逐步添加。

ProtoBuf 常用序列化/反序列化API
https://blog.csdn.net/sealyao/article/details/6940245

Protobuf C++ serialize到char*的方法
https://www.cnblogs.com/brainy/archive/2012/05/13/2498660.html

另外一篇入门介绍的
https://blog.csdn.net/u014696921/article/details/52200010

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值