Linux下protobuf-c的使用、
一、下载安装包
下载protobuf2.6.0以上版本(protobuf-c)的依赖,与protobuf-c。
二、进行安装
(1)安装依赖
sudo yum -y install autoconf automake libtool make g++ unzip
(2)安装protobuf
./autogen
./configure
make
make check
sudo make install
sudo ldconfig
(3)安装protobuf-c
./autogen
./configure
make
make check
sudo make install
sudo ldconfig
三、demo
(1)proto文件
syntax="proto2";
message Person
{
optional string name = 1;
optional int64 age = 2;
optional string sex = 3;
optional string id = 4;
}
生成头文件与源文件:protoc-c --c_out ./ ./msg.proto
(2)demo源文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "msg.pb-c.h"
int main(int argc, char **argv)
{
Person p = PERSON__INIT;
Person *q;
p.age = 15;
size_t len = 0;
char *buf = NULL;
p.name = (char*)malloc(10);
p.sex = (char*)malloc(10);
p.id = (char*)malloc(20);
//可选字段填充后需要手动值标志位为真
p.has_age = 1;
strcpy(p.name, "zhangsan");
strcpy(p.sex, "male");
strcpy(p.id, "20162349801");
len = person__get_packed_size(&p);
buf = (char*)malloc(len);
memset(buf, 0x00, len);
person__pack(&p, buf);
printf("%s\n", buf);
q = person__unpack(NULL, len, buf);
printf("Name:%s\tage:%d\tsex:%s\tid:%s\n", q->name, q->age, q->sex, q->id);
//释放反序列化结构内存
person__free_unpacked(q, NULL);
//手动释放内存
free(p.name), free(p.sex), free(p.id);
return 0;
}
gcc -lprotobuf-c -I./ ./msg.pb-c.c ./test.c -o test
./test
如果报错找不到protobuf-c库:
export LD_LIBRARY_PATH=protobuf-c库所在文件夹路径