我使用 protobuf-net 序列化了数据,并且能够在 C# 中进行相同的处理。
放置一个 C# 虚拟 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();
到目前为止一切顺利...这里没有问题。但是当我尝试使用 Protocol Buffer 在 C++ 中反序列化相同内容时,我无法获得正确的数据
cpp代码...
GOOGLE_PROTOBUF_VERIFY_VERSION;
string fpath = "animal.bin";
fstream input(fpath, ios::in | ios::binary);
if (!input)
{
cerr << "failed to open " << fpath << endl;
return false;
}
ZeroCopyInputStream *raw_in = new IstreamInputStream(&input);
CodedInputStream *coded_in = new CodedInputStream(raw_in);
google::protobuf::uint32 n;
std::string tmpStr;
animal::animalInfo animalList;
coded_in->ReadVarint32(&n);
cout << "# " << n << endl; //output: #10
coded_in->ReadRaw(&tmpStr,n); //tmpStr shows data like >>1..Rat..Ch
animalList.ParseFromArray(&tmpStr,1);//Not sure if this is correct usage?
我确定我犯了一个错误,但无法理解哪里出了问题......已经阅读并重读了很多关于此的帖子,但看不出还有什么问题
使用 Protocol Buffer2.5、protobuf-netR622、Visual Studio 2010
最佳答案
我认为您只是不匹配 header ;长度前缀和字段 header (字段 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);
关于c# - 使用 protobuf-net 发布反序列化 (protocolBuffer) 序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473083/