Java 协议缓冲区分隔 I/O 函数的 C 等效项
在 C 和 Java 中,都需要读写多个协议缓冲来自文件的消息。 Java 版本 2.1.0 为此提供了一组“分隔”I/O 函数:
- parseDelimitedFrom
- mergeDelimitedFrom
- writeDelimitedTo
这些函数有助于在每条消息之前附加长度前缀。然而,目前尚不清楚 C 中是否存在这样的功能。
C 等效项的存在
最初,这些 Java 函数没有直接的 C 等效项。然而,从版本 3.3.0 开始,C 现在在 google/protobuf/util/delimited_message_util.h 中提供了分隔消息实用函数。
大小前缀格式
For如果用户希望在这些官方实用程序发布之前用 C 语言实现自己的解析器,那么了解 Java API 附加的大小前缀的传输格式非常重要。该格式遵循以下准则:
- 分隔符甚至必须出现在第一条消息之前。
- 消息的大小被编码为 32 位 varint。
- 1 字节分隔符字节 (0x0A) 终止每条消息,下一条长度前缀消息紧随其后开始。
优化的 C 实现
官方 C 实用函数发布后,发现了最初提出的实现中缺少的一些优化。下面提供的这些优化函数可提高性能并避免潜在错误:
<code class="cpp">bool writeDelimitedTo( const google::protobuf::MessageLite& message, google::protobuf::io::ZeroCopyOutputStream* rawOutput) { // Create a new coded stream for each message. google::protobuf::io::CodedOutputStream output(rawOutput); // Write the message size. const int size = message.ByteSize(); output.WriteVarint32(size); // Serialize the message directly to the output buffer if possible. uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != NULL) { message.SerializeWithCachedSizesToArray(buffer); } else { // Use a slower path if the message spans multiple buffers. message.SerializeWithCachedSizes(&output); if (output.HadError()) return false; } return true; } bool readDelimitedFrom( google::protobuf::io::ZeroCopyInputStream* rawInput, google::protobuf::MessageLite* message) { // Create a new coded stream for each message. google::protobuf::io::CodedInputStream input(rawInput); // Read the message size. uint32_t size; if (!input.ReadVarint32(&size)) return false; // Set a read limit to enforce the 64 MB per-message size constraint. google::protobuf::io::CodedInputStream::Limit limit = input.PushLimit(size); // Parse the message. if (!message->MergeFromCodedStream(&input)) return false; if (!input.ConsumedEntireMessage()) return false; // Remove the read limit. input.PopLimit(limit); return true; }</code>
以上是如何使用定界 I/O 在 C 中编码和解码 Protocol Buffers 消息?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Atom编辑器mac版下载
最流行的的开源编辑器

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。