I am using 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() Any ideas?
Asked
Active
Viewed 3,546 times
1

jpa
- 10,351
- 1
- 28
- 45

Chuck Claunch
- 1,624
- 1
- 17
- 29
1 Answers
1
In C, a binary string is just an uint8_t array. (Note that a normal C string cannot contain binary data so it cannot be used to store protobuf messages.)
So the pb_ostream_from_buffer() is the correct way to get the result as a "string".
Taking from the simple.c example:
uint8_t buffer[128];
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
status = pb_encode(&stream, SimpleMessage_fields, &message);
After that the encoded message is in buffer
and has length of stream.bytes_written
. That is the string you want.

jpa
- 10,351
- 1
- 28
- 45
-
I'm not following what you're saying about a "normal C string cannot contain binary data". Is that not what the standard protobuf serializeToString() is doing? Basically I want to export the "string" back to another system which will then send it via UDP. – Chuck Claunch Jul 08 '15 at 17:20
-
@ChuckClaunch If you are referring to serializeToString() in the C++ protobuf library, it serializes to a C++ string, which can indeed contain binary data. A C string is null-terminated, and cannot contain null bytes so it cannot contain binary data. Nanopb is a C library, thus it does not serialize directly to C++ strings (though writing your own wrapper is relatively straightforward). – jpa Jul 09 '15 at 14:12
-
Ahh, yes that makes sense now. I did end up solving my issue by just passing the the uint8_t array back out and letting the user code handle the sending with that. Thanks for the answer! – Chuck Claunch Jul 09 '15 at 20:37
-
@jpa I there any standard way to send encoded message as a string? I ended up converting to string contains hex numbers but it gets a double size for the buffer. – Masoud Rahimi Dec 12 '18 at 06:41
-
@MasoudR. Reading your other question, it seems your main trouble is the 0 bytes in the binary data. Trying to avoid them by any encoding (e.g. base64, cobs) always increases the size of the data. – jpa Dec 12 '18 at 07:01