$ cat address.proto
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
message Person {
required string name = 1;
required int32 id = 2;
repeated PhoneNumber phone = 4;
optional string email = 3;
}
message AddressBook {
repeated Person person = 2;
optional int32 id = 1;
}
$ cat address.options
com.mbsoft.PhoneNumber.number max_size:16
com.mbsoft.Person.name max_size:128
com.mbsoft.Person.email max_size:128
com.mbsoft.Person.phone max_count:4
com.mbsoft.Addressbook.person max_count:2
$ hexdump input.bin
0000000 320a 030a 6161 1061 1a6f 6107 6140 632e
0000010 6d6f 0f22 0b0a 3131 3131 3131 3131 3131
0000020 1031 2201 0a0f 320b 3232 3232 3232 3232
0000030 3232 0010 330a 030a 6262 1062 01de 071a
0000040 4062 2e62 6f63 226d 0a0f 330b 3333 3333
0000050 3333 3333 3333 0110 0f22 0b0a 3434 3434
0000060 3434 3434 3434 1034 0000
0000069
$ cat instream.bin | protoc --decode=AddressBook address.proto
1 {
1: "aaa"
2: 111
3: "a...@a.com"
4 {
1: "11111111111"
2: 1
}
4 {
1: "22222222222"
2: 0
}
}
1 {
1: "bbb"
2: 222
3: "b...@b.com"
4 {
1: "33333333333"
2: 1
}
4 {
1: "44444444444"
2: 0
}
}
#include <stdio.h>
#include <pb_encode.h>
#include <pb_decode.h>
#include "address.pb.h"
int main()
{
/* This is the buffer where we will store our message. */
uint8_t buffer[10240];
size_t message_length;
bool status;
/* Now we could transmit the message over network, store it in a file or
* wrap it to a pigeon's leg.
*/
/* But because we are lazy, we will just decode it immediately. */
{
/* Allocate space for the decoded message. */
com_mbsoft_AddressBook address_book;
FILE *fp = fopen("input.bin", "rb");
message_length = 0;
/* I HAVE PRINTED ALL DATA, IT IS THE SAME AS INPUT.BIN */
#if 0
while (fread(&buffer[message_length], 1, 1, fp)) {
//printf("%02X ", buffer[message_length]);
message_length ++;
//if (message_length % 16 == 0) printf("\n");
}
printf("\n");
#else
message_length = fread(buffer, 1, sizeof(buffer), fp);
#endif
fclose(fp);
printf("length read: %d, feof = %d, ferror = %d\n", message_length,
feof(fp), ferror(fp));
/* Create a stream that reads from the buffer. */
pb_istream_t stream = pb_istream_from_buffer(buffer,
message_length);
/* Now we are ready to decode the message. */
status = pb_decode(&stream, com_mbsoft_AddressBook_fields,
&address_book);
/* Check for errors... */
if (!status)
{
printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
return 1;
}
/* Print the data contained in the message. */
printf("has_id is %s\n", address_book.has_id ? "true" : "false");
printf("Your lucky number was %d!\n", address_book.id);
}
return 0;
}
You are right, I misunderstood values in *.proto file, and made the field number different.
It works very well now. Thanks for your great job.