构造 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