Search code examples
cprotocol-buffersnanopb

Nanopb get string from pb_ostream_t


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?


Solution

  • 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.