README.txt 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. Nanopb example "using_union_messages"
  2. =====================================
  3. Union messages is a common technique in Google Protocol Buffers used to
  4. represent a group of messages, only one of which is passed at a time.
  5. It is described in Google's documentation:
  6. https://developers.google.com/protocol-buffers/docs/techniques#union
  7. This directory contains an example on how to encode and decode union messages
  8. with minimal memory usage. Usually, nanopb would allocate space to store
  9. all of the possible messages at the same time, even though at most one of
  10. them will be used at a time.
  11. By using some of the lower level nanopb APIs, we can manually generate the
  12. top level message, so that we only need to allocate the one submessage that
  13. we actually want. Similarly when decoding, we can manually read the tag of
  14. the top level message, and only then allocate the memory for the submessage
  15. after we already know its type.
  16. NOTE: There is a newer protobuf feature called `oneof` that is also supported
  17. by nanopb. It might be a better option for new code.
  18. Example usage
  19. -------------
  20. Type `make` to run the example. It will build it and run commands like
  21. following:
  22. ./encode 1 | ./decode
  23. Got MsgType1: 42
  24. ./encode 2 | ./decode
  25. Got MsgType2: true
  26. ./encode 3 | ./decode
  27. Got MsgType3: 3 1415
  28. This simply demonstrates that the "decode" program has correctly identified
  29. the type of the received message, and managed to decode it.
  30. Details of implementation
  31. -------------------------
  32. unionproto.proto contains the protocol used in the example. It consists of
  33. three messages: MsgType1, MsgType2 and MsgType3, which are collected together
  34. into UnionMessage.
  35. encode.c takes one command line argument, which should be a number 1-3. It
  36. then fills in and encodes the corresponding message, and writes it to stdout.
  37. decode.c reads a UnionMessage from stdin. Then it calls the function
  38. decode_unionmessage_type() to determine the type of the message. After that,
  39. the corresponding message is decoded and the contents of it printed to the
  40. screen.