1 protobuf简介
Protobuf的功能是将是结构化数据转化为二进制流,比如,struct _msg{ Int val;}msg;Unsigned char streambuf[256];Msg A;A.val = 1;Protobuf.encode(streambuf,A);如上,将结构化数据转为二进制流存到streambuf。使用时,再将二进制充转化为结构化数据,如:Msg B;Protobuf.decode(streambuf,B);
则B.val制就是A.val了。好处应该是为了节省空间吧。
3)转化出来的文件配合protobuf的库或者源文件就可以在目标环境下使用了
第一段是将结构数据转为二进制流:
/* Encode our message */ { /* Allocate space on the stack to store the message data. * * Nanopb generates simple struct definitions for all the messages. * - check out the contents of simple.pb.h! * It is a good idea to always initialize your structures * so that you do not have garbage data from RAM in there. */ SimpleMessage message = SimpleMessage_init_zero; /* Create a stream that will write to our buffer. */ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); /* Fill in the lucky number */ message.lucky_number = 13; /* Now we are ready to encode the message! */ status = pb_encode(&stream, SimpleMessage_fields, &message); message_length = stream.bytes_written; /* Then just check for any errors.. */ if (!status) { printf("Encoding failed: %s\n", PB_GET_ERROR(&stream)); return 1; } }如上,是将message结构数据转为二进制流存到buffer里。这个buffer可以存到文件或者发送到网络。
第二段是将二进制流转化为结构数据:
{ /* Allocate space for the decoded message. */ SimpleMessage message = SimpleMessage_init_zero; /* 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, SimpleMessage_fields, &message); /* Check for errors... */ if (!status) { printf("Decoding failed: %s\n", PB_GET_ERROR(&stream)); return 1; } /* Print the data contained in the message. */ printf("Your lucky number was %d!\n", message.lucky_number); }如上,是将二进制流buffer转为message结构数据。 以上,都是在LINUX环境下的验证,最后我们要将所需的C文件移植到嵌入式平台上。打开Makefile脚本,可以看到,总共需要的文件是: simple.c simple.pb.c pb_encode.c pb_decode.c pb_common.c Simple.c是main函数,是不用移植的,所以总共就除simple.c的4个文件,以及它们对应的头文件:pb_encode.h、pb_decode.h、pb_common.h、pb.h、simple.pb.h,simple.pb.h在simple目录下,其它的在nanopb-0.3.5-linux-x86目录下。将这些文件拷到嵌入式平台下编译就完成了。