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

构造  Repeated Submessages

构造一个 emessage.proto 文件
message Submessage
{
    required int32 value=1;
}

message EMessage
{
    repeated Submessage a=1;
}

下面给出打包代码:

#include<stdio.h>
#include<stdlib.h>
#include"dmessage.pb-c.h"

int main (int argc,constchar* argv[])
{
    Submessage**subs;
    void*buf;
    unsigned len;
    subs = malloc (sizeof(Submessage*)*(argc-1));
    for(i =1; i < argc; i++)
      {
        subs[i-1]= malloc (sizeof(Submessage));
        submessage__init (subs[i-1]);
        subs[i-1]->value = atoi(argv[i]);
      }    
    msg.n_a = argc-1;
    msg.a = subs;
    len = emessage__get_packed_size (&msg);// This is the calculated packing length
    buf = malloc (len);                    // Allocate memory
   emessage__pack (&msg, buf);             // Pack msg, including submessages

    fprintf(stderr,"Writing %d serializedbytes\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
   for(i =1; i < argc; i++)
     free (subs[i]);
   free (subs);
   return0;
}

值得注意的是重复域创建了两个域,n_a  submessagesd 的个数,另一个是submessages 自己。(理解这句话需要阅读.proto文件生成的源代码)


下面给出解包的源代码

#include <stdio.h>
#include"emessage.pb-c.h"
#define MAX_MSG_SIZE 4096

int main (int argc,constchar* argv[])
{
    EMessage*msg;
    char c;int i=0;
    uint8_tbuf[MAX_MSG_SIZE];// Input data container for bytes
   
    while(fread(&c,1,1,stdin)!=0)
    {
       if(i >= MAX_MSG_SIZE)
       {
           fprintf(stderr,"message too long for allocatedbuffer\n");
           return1;
       }
       buf[i++]= c;
    }
   
    msg = emessage__unpack(NULL,i,buf);// Deserialize the serialized input
    if(msg == NULL)
    {
       fprintf(stderr,"error unpacking incomingmessage\n");
       return1;
    }
    for(i =0; i < msg->n_a; i++)
      printf ("%d\n", msg->a[i]->value);
   
   emessage__free_unpacked(msg,NULL);
   
    return0;
}

命令行运行:

./emessage_serialize 45|./emessage_deserialize
Writing:8 serialized bytes
4
5
./emessage_serialize 458|./emessage_deserialize
4
5
8

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值