c# - 使用 protobuf-net 发布反序列化 (protocolBuffer) 序列化数据

标签 c# c++ protocol-buffers protobuf-net

我使用 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/

相关文章:

c# - 使用 Linq 搜索两个项目的组合

c# - 单击 "X"按钮时要求确认

c++ - 如何打开 Visual Studio Express 2013 for Windows Desktop (C++)?

C++ : Function return String in Static Library give Error : expected '=' , ',' , ';' , 'asm' 或 '__attribute__' token 之前的 ':'

c++ - Protobuf设计

c# - 在 UWP 应用程序中序列化对象

python - Mac OSX 10.10 找不到 opencv 库

c++ - 如何在另一个文件中使用一个 .proto 文件的枚举?

c++ - 链接错误,即使我包含了标题和库(这是自编译的)

c# - 如果它是销售收据的一部分,您如何从 Quickbooks 交易中找到付款行的 TxnLineID?