encode_map.c 996 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /* Encode a message using map field */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pb_encode.h>
  5. #include "map.pb.h"
  6. #include "test_helpers.h"
  7. int main(int argc, char **argv)
  8. {
  9. uint8_t buffer[MyMessage_size];
  10. MyMessage msg = MyMessage_init_zero;
  11. pb_ostream_t stream;
  12. /* Fill in the map entries */
  13. msg.numbers_count = 3;
  14. strncpy(msg.numbers[0].key, "one", sizeof(msg.numbers[0].key));
  15. strncpy(msg.numbers[1].key, "two", sizeof(msg.numbers[1].key));
  16. strncpy(msg.numbers[2].key, "seven", sizeof(msg.numbers[2].key));
  17. msg.numbers[0].value = 1;
  18. msg.numbers[1].value = 2;
  19. msg.numbers[2].value = 7;
  20. stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  21. if (pb_encode(&stream, MyMessage_fields, &msg))
  22. {
  23. SET_BINARY_MODE(stdout);
  24. fwrite(buffer, 1, stream.bytes_written, stdout);
  25. return 0;
  26. }
  27. else
  28. {
  29. fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
  30. return 1;
  31. }
  32. }