根据语言指导手册创建一个简单的文件:amessage.proto ,内容如下
message AMessage
{
required int32 a=1;
optional int32 b=2;
}
t通过命令行产生相应的.h和.c源文件。 # protoc-c --c_out=. amessage.proto
C文件如下所示
#include<stdio.h>
#include<stdlib.h>
#include"amessage.pb-c.h"
int main (int argc,constchar* argv[])
{
AMessage msg = AMESSAGE__INIT;// AMessage
void*buf; // Buffer to storeserialized data
unsigned len; // Length of serialized data
if(argc !=2&& argc !=3)
{ // Allow one or twointegers
fprintf(stderr,"usage:amessage a [b]\n");
return1;
}
msg.a = atoi(argv[1]);
if(argc ==3){ msg.has_b =1; msg.b = atoi(argv[2]);}
len =amessage__get_packed_size(&msg);
buf = malloc(len);
amessage__pack(&msg,buf);
fprintf(stderr,"Writing %dserialized bytes\n",len);// See the lengthof message
fwrite(buf,len,1,stdout);// Write to stdoutto allow direct command line piping
free(buf);// Free theallocated serialized buffer
return0;
}
注意以下几点:
- 使用A_MESSAGE__INIT宏创建信息的架构
- 参数b是可选的
- amessage__get_packed_size返回数据包的长度。
- a_message__pack 对你设计的信息进行打包。
下面给出对amessage解包的代码。
#include<stdio.h>
#include<stdlib.h>
#include"amessage.pb-c.h"
#define MAX_MSG_SIZE 1024
static size_t
read_buffer (unsigned max_length, uint8_t *out)
{
size_t cur_len =0;
uint8_t c;
while((nread=fread(out+ cur_len,1, max_length - cur_len, stdin))!=0)
{
cur_len += nread;
if(cur_len == max_length)
{
fprintf(stderr,"max messagelength exceeded\n");
exit(1);
}
}
return cur_len;
}
int main (int argc,constchar* argv[])
{
AMessage*msg;
// Read packed message from standard-input.
uint8_t buf[MAX_MSG_SIZE];
size_t msg_len = read_buffer (MAX_MSG_SIZE, buf);
// Unpack the message using protobuf-c.
msg = amessage__unpack(NULL, msg_len, buf);
if(msg == NULL)
{
fprintf(stderr,"errorunpacking incoming message\n");
exit(1);
}
// display the message's fields.
printf("Received: a=%d",msg->a); // required field
if(msg->has_b) // handle optionalfield
printf(" b=%d",msg->b);
printf("\n");
// Free the unpacked message
amessage__free_unpacked(msg, NULL);
return0;
}
编译连接的时候要包含 '-lprotobuf-c',否则编译不通过
Test by piping one program into the next atcommand line:
#./amessage_serialize 10 2 | ./amessage_deserialize ---->使用管道命令
Writing:4 serialized bytes
Received: a=10 b=2