8 /* This is the buffer where we will store our message. */
10 size_t message_length;
13 /* Encode our message */
15 /* Allocate space on the stack to store the message data.
17 * Nanopb generates simple struct definitions for all the messages.
18 * - check out the contents of simple.pb.h! */
19 SimpleMessage message;
21 /* Create a stream that will write to our buffer. */
22 pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
24 /* Fill in the lucky number */
25 message.lucky_number = 13;
27 /* Now we are ready to encode the message! */
28 status = pb_encode(&stream, SimpleMessage_fields, &message);
29 message_length = stream.bytes_written;
31 /* Then just check for any errors.. */
34 printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
39 /* Now we could transmit the message over network, store it in a file or
40 * wrap it to a pigeon's leg.
43 /* But because we are lazy, we will just decode it immediately. */
46 /* Allocate space for the decoded message. */
47 SimpleMessage message;
49 /* Create a stream that reads from the buffer. */
50 pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
52 /* Now we are ready to decode the message. */
53 status = pb_decode(&stream, SimpleMessage_fields, &message);
55 /* Check for errors... */
58 printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
62 /* Print the data contained in the message. */
63 printf("Your lucky number was %d!\n", message.lucky_number);