protobuf的C简单的代码例子(一)

根据语言指导手册创建一个简单的文件:amessage.proto ,内容如下

   message AMessage
   {
      required int32 a=1;
      optional int32 b=2;
   }

t通过命令行产生相应的.h和.c源文件。  # protoc---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 |  ./amessage_deserialize    ---->使用管道命令
Writing:4 serialized bytes
Received: a=10 b=2

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值