protobuf-c编译成c语言,protobuf-c应用样例

源码

编译

./autogen.sh && ./configure && make && make install

应用

根据协议格式生成源码与头文件

amessage.proto 文件内容如下:

message AMessage {

required int32 a=1;

optional int32 b=2;

}

根据amessage.proto 生成C语言头文件与源码

protoc-c --c_out=. amessage.proto

生成如下文件:

amessage.pb-c.c

amessage.pb-c.h

使用样例:

封装协议:pack.c

#include

#include

#include "amessage.pb-c.h"

int main (int argc, const char * argv[])

{

AMessage msg = AMESSAGE__INIT; // AMessage

void *buf; // Buffer to store serialized data

unsigned len; // Length of serialized data

if (argc != 2 && argc != 3)

{ // Allow one or two integers

fprintf(stderr,"usage: amessage a [b]\n");

return 1;

}

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 %d serialized bytes\n",len); // See the length of message

fwrite(buf,len,1,stdout); // Write to stdout to allow direct command line piping

free(buf); // Free the allocated serialized buffer

return 0;

}

解包协议:unpack.c

#include

#include

#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;

size_t nread;

while ((nread=fread(out + cur_len, 1, max_length - cur_len, stdin)) != 0)

{

cur_len += nread;

if (cur_len == max_length)

{

fprintf(stderr, "max message length exceeded\n");

exit(1);

}

}

return cur_len;

}

int main (int argc, const char * 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, "error unpacking incoming message\n");

exit(1);

}

// display the message's fields.

printf("Received: a=%d",msg->a); // required field

if (msg->has_b) // handle optional field

printf(" b=%d",msg->b);

printf("\n");

// Free the unpacked message

amessage__free_unpacked(msg, NULL);

return 0;

}

编译样例

gcc -o serialize pack.c amessage.pb-c.c -lprotobuf-c

gcc -o deserialize unpack.c amessage.pb-c.c -lprotobuf-c

执行结果

./serialize 10 2 | ./deserialize

Writing 4 serialized bytes

Received: a=10 b=2

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值