Nanopb:将已编码的消息添加为重复字段
我有以下形式的消息:
message OuterMessage {
repeated InnerMessage msg = 1;
}
我想通过附加已编码的 InnerMessage 实例来组成 OuterMessage 实例。有没有合法的方法可以用 nanopbs 做到这一点?
I have message of the form:
message OuterMessage {
repeated InnerMessage msg = 1;
}
I would like to compose an instance of OuterMessage by appending already encoded instances of InnerMessage. Is there a legit way to do this with nanopbs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法:
通过调用
pb_encode_tag_for_field()
和pb_encode_string()
手动编码外部消息。在 protobuf 中,子消息相当于有线格式中的字符串。对重复字段使用回调。在回调中,您可以执行与上面 1. 相同的操作,但还可以自动编码外部消息中的任何其他字段。
仅将标头(标记和长度)编码到单独的缓冲区中,发送它,然后发送已编码的消息。这避免了复制数据。
在子消息字段上设置选项
(nanopb).type_override = TYPE_BYTES
,以将其生成为bytes
字段。然后你可以在其中设置编码内容。但这种方法效率很低,因为它会导致多次复制消息数据。There are a few ways:
Encode outer message manually by calling
pb_encode_tag_for_field()
andpb_encode_string()
. In protobuf, submessages are equivalent to strings in the wire format.Use callbacks for the repeated field. In the callback you can do the same as 1. above, but also get automatic encoding of any other fields in the outer message.
Encode just the header (tag and length) to a separate buffer, send it and then send your already encoded message. This avoids having to copy the data around.
Set option
(nanopb).type_override = TYPE_BYTES
on the submessage field, to generate it as if was abytes
field instead. Then you can set the encoded content inside that. But this approach is quite inefficient, as it results in copying the message data multiple times.