gpt4 book ai didi

c# - 如何使用 protobuf-net 读取 fixed32 整数?

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:15 25 4
gpt4 key购买 nike

这似乎是一个基本问题,但我有疑问,可能是因为我使用 2 个不同的库来写入和读取数据。我的 Write 程序是用 c++ 编写的,它使用了谷歌的 Protocol Buffer 库。我的阅读器是在 .NET c# 中实现的。

在写程序时,我写了一个文件头如下。

coded_output->WriteLittleEndian32(BIN_START_MAGIC_NUMBER);
coded_output->WriteLittleEndian32(major_version);
coded_output->WriteLittleEndian32(minor_version);
coded_output->WriteVarint32(strlen(_region));
coded_output->WriteRaw(_region, strlen(_region));
coded_output->WriteLittleEndian32(_offset);

读取上述字段在C#中对应的函数是什么?我了解如何读取 Protocol Buffer 消息但不确定如何读取上述数据。

问候,好吧

最佳答案

该文件头不是有效的 protobuf 序列,因此 protobuf-net 中的标准读取机制不适合读取它 - 事实上,ProtoReader不会让自己进入阅读状态,因为它是无效的。然而!要读取 little-endian 32 位数字,您可以使用:

int x, int y; // ignore
int value = ProtoReader.ReadLengthPrefix(stream, false, PrefixStyle.Fixed32,
out x, out y);

假设编码流使用标准的 protobuf 约定,字符串被写为 varint 长度前缀,然后是 UTF-8,因此您可以使用:

int x, int y; // ignore
int length = ProtoReader.ReadLengthPrefix(stream, false, PrefixStyle.Base128,
out x, out y);
byte[] bytes = new byte[length];
int read, offset = 0;
while(length > 0 && (read = stream.Read(bytes, offset, length)) > 0) {
offset += read;
length = read;
}
if(length > 0) throw new EndOfStreamException();
string s = Encoding.UTF8.GetString(bytes);

如果您真的需要,我可能可以为您打包更方便的;它们目前没有暴露,因为那不是 protobuf ;p

关于c# - 如何使用 protobuf-net 读取 fixed32 整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8412306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com