将多个消息存储在一个协议缓冲区二进制文件中 [英] Storing multiple messages in one protocol buffer binary file

查看:102
本文介绍了将多个消息存储在一个协议缓冲区二进制文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有重复的邮件,我想存储在一个单一的文件。目前,我必须将此重复消息包装在另一个消息中。是否有办法解决这个问题?

I have repeating messages which I want to store in a single file. Currently I have to wrap this repeating message in another message. Is there a way around this?

package foo;

message Box {
  required int32 tl_x = 1;
  required int32 tl_y = 2;
  required int32 w = 3;
  required int32 h = 4;
}

message Boxes {
  repeated Box boxes = 1;
}


推荐答案

Protocol Buffers文档的http://code.google.com/apis/protocolbuffers/docs/techniques.html#streaming\">技术部分说明了重复的邮件:

Here's what "Techniques" section of the Protocol Buffers documentation says about repeated messages:


如果你想写多个消息
到一个单一的文件或流,它是up
你跟踪一个
消息结束,下一个开始。
协议缓冲区有线格式不是
自分隔,所以协议缓冲区
解析器不能确定
消息自己结束的位置。最简单的
方法来解决这个问题是在
之前写入
每个消息的大小写消息本身。当
读取消息时,读取​​大小为
,然后将字节读入
单独的缓冲区,然后从
缓冲区解析。 (如果你想避免复制
字节到一个单独的缓冲区,检查
CodedInputStream类(在
C ++和Java中),可以告诉
限制读取到一定数量的
字节。)

If you want to write multiple messages to a single file or stream, it is up to you to keep track of where one message ends and the next begins. The Protocol Buffer wire format is not self-delimiting, so protocol buffer parsers cannot determine where a message ends on their own. The easiest way to solve this problem is to write the size of each message before you write the message itself. When you read the messages back in, you read the size, then read the bytes into a separate buffer, then parse from that buffer. (If you want to avoid copying bytes to a separate buffer, check out the CodedInputStream class (in both C++ and Java) which can be told to limit reads to a certain number of bytes.)

在C ++和Java中还有一种常规的实现方式。有关详细信息,请参阅此Stack Overflow线程:在Java中,协议缓冲区分隔的I / O函数是否有C ++等同物?

There's also a conventional way of implementing this in C++ and Java. Take a look at this Stack Overflow thread for details: Are there C++ equivalents for the Protocol Buffers delimited I/O functions in Java?

这篇关于将多个消息存储在一个协议缓冲区二进制文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆