关于什么是protobuf,网上搜搜一大堆,很多人用的都还是json,以为json是多种语言传输数据是万能的,看完了protobuf的实现,就明白了简单高效才是王道。
2、执行命令生成.c和.h文件,protoc-c可执行文件已经预先生成了,编译protobuf-c参考http://blog.csdn.net/code_style/article/details/54375785
./protoc-c json.proto
3、写示例代码main.c:
解析:protobuf的核心就是pack和unpack以及最后的free_unpack,比如客户端要给服务端发送一个msg,客户端把pack好的pBuf缓冲区数据直接发出去,服务端收到数据之后,再从pBuf里面“取出”out结构体指针指向的msg,最后调用free_unpacked释放out就可以了。
//main.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "json.pb-c.h"
int main(void)
{
Response msg,*out;
unsigned char *pBuf;
unsigned int Len;
response__init(&msg); //init default
msg.led_on=1;
msg.node_id="5149013220584027";
msg.parent_id="5149013108519750";
msg.uuid="121212121";
Len=response__get_packed_size(&msg);
printf("msg pack size %d\n",Len);
pBuf=malloc(Len);
if(pBuf)
{
response__pack(&msg,pBuf); //construct msg to pBuf
FILE *fp =fopen("protobuf.txt","wb+"); //output raw
if(fp)
{
fwrite(pBuf,Len,1,fp);
fclose(fp);
fp=NULL;
}
out=response__unpack(NULL,Len,pBuf);
if(out)
{
printf("out->led_on=%d\n",((Response*)out)->led_on);
printf("out->node_id=%s\n",((Response*)out)->node_id);
printf("out->parent_id=%s\n",((Response*)out)->parent_id);
printf("out->uuid=%s\n",((Response*)out)->uuid);
response__free_unpacked(out,NULL);
}
}
printf("End\n");
}
4、编译注意事项
附录:
4、最后不得不佩服,google出品必属精品。
317



被折叠的 条评论
为什么被折叠?



