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