Nanopb 从 pb_ostream_t 获取字符串
Nanopb get string from pb_ostream_t
我正在使用nanopb so I can implement protobuf with some small, cross compiled code. I have the base of it working but would like to get the encoded protobuf message as a string for sending via UDP (on another system). Normally with the full blown protobuf library you do something like message.serializeToString()
. Nanopb doesn't seem to have that, but surely it's a common thing to do. The examples given from nanopb use their pb_ostream_t struct and pb_ostream_from_buffer()有什么想法吗?
在 C 语言中,二进制字符串就是一个 uint8_t 数组。 (请注意,普通的 C 字符串不能包含二进制数据,因此不能用于存储 protobuf 消息。)
所以 pb_ostream_from_buffer() 是获得 "string" 结果的正确方法。
uint8_t buffer[128];
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
status = pb_encode(&stream, SimpleMessage_fields, &message);
之后,编码消息在 buffer
中,长度为 stream.bytes_written
。这就是你想要的字符串。
我正在使用nanopb so I can implement protobuf with some small, cross compiled code. I have the base of it working but would like to get the encoded protobuf message as a string for sending via UDP (on another system). Normally with the full blown protobuf library you do something like message.serializeToString()
. Nanopb doesn't seem to have that, but surely it's a common thing to do. The examples given from nanopb use their pb_ostream_t struct and pb_ostream_from_buffer()有什么想法吗?
在 C 语言中,二进制字符串就是一个 uint8_t 数组。 (请注意,普通的 C 字符串不能包含二进制数据,因此不能用于存储 protobuf 消息。)
所以 pb_ostream_from_buffer() 是获得 "string" 结果的正确方法。
uint8_t buffer[128];
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
status = pb_encode(&stream, SimpleMessage_fields, &message);
之后,编码消息在 buffer
中,长度为 stream.bytes_written
。这就是你想要的字符串。