使用protobuf-net发布反序列化(protocolBuffer)序列化数据
我使用protobuf-net对数据进行了序列化,并且能够在C#中进行相同的处理。
放一个C#dummy w#
var file = File.Create("animal.bin"); //Creating Msg - Fill the Data animal.id = "1"; animal.Name = "Rat"; animal.host = "Cheetha"; ProtoBuf.Serializer.SerializeWithLengthPrefix(file, animal, PrefixStyle.Base128, 1); animal.id = "2"; animal.Name = "Cat"; animal.host = "Cheetha"; ProtoBuf.Serializer.SerializeWithLengthPrefix(file, animal, PrefixStyle.Base128, 1); .... animal.id = "4"; animal.name = "Cheetha"; animal.host = "Cheetha"; ProtoBuf.Serializer.SerializeWithLengthPrefix(file, animal, PrefixStyle.Base128, 1); //Done Creating Msg file.Close();
到目前为止一切都很好……这里没有问题。 但是当我尝试使用协议缓冲区在C ++中反序列化相同时,我无法获得正确的数据
cpp代码……
GOOGLE_PROTOBUF_VERIFY_VERSION; string fpath = "animal.bin"; fstream input(fpath, ios::in | ios::binary); if (!input) { cerr << "failed to open " << fpath <ReadVarint32(&n); cout << "# " << n <ReadRaw(&tmpStr,n); //tmpStr shows data like >>1..Rat..Ch animalList.ParseFromArray(&tmpStr,1);//Not sure if this is correct usage?
我确信我犯了一个错误但却无法理解什么是错误的……已阅读并重读了很多post,但没有看到什么仍然是错误的
使用Protocol Buffer2.5,protobuf-netR622,Visual Studio 2010
我认为你只是不匹配标题; 长度前缀和字段标题(字段1)是两个 “varint”; 第一个 “varint”将始终为十进制10(10表示:字段1,长度为前缀)。 第二个 “varint”告诉您下一个数据的长度。 所以 – 如果你想手动解码它,你会再次调用ReadVarint32
。 我不熟悉ReadRaw
,但如果第二个参数是要读取的字节数,那么它会去那里 ,即
coded_in->ReadVarint32(&n); // field header // assert: n === 10 coded_in->ReadVarint32(&n); // length coded_in->ReadRaw(&tmpStr,n);
或者,只使用包装器对象 – 即
message animals { repeated animal items = 1; }
并将其反序列化为animals
实例 – 这使用完全相同的布局。 这里唯一的区别是它会一次性加载所有项目 – 所以如果你正在阅读很长的流,它可能会有问题。
另一种选择是: 不添加字段标题 :
Serializer.SerializeWithLengthPrefix(file, animal, PrefixStyle.Base128, 0);
然后你只会读一个“varint”:
coded_in->ReadVarint32(&n); // length coded_in->ReadRaw(&tmpStr,n);