创建dmessage.proto 文件:
message Submessage
{
required int32 value=1;
}
message DMessage
{
required Submessage a=1;
optional Submessage b=2;
}
DMessage包含一个或者二个整型(a 是必要的整型数据,b是可选的整型数据)
#include<stdio.h>
#include<stdlib.h>
#include"dmessage.pb-c.h"
int main (int argc,constchar* argv[])
{
DMessage msg = DMESSAGE__INIT; // DMESSAGE
Submessage sub1 = SUBMESSAGE__INIT;// SUBMESSAGE A
Submessage sub2 = SUBMESSAGE__INIT;// SUBMESSAGE B
void*buf;
unsigned len;
if(argc !=2&& argc !=3)
{ // Allow one or twointegers
fprintf(stderr,"usage:dmessage a [b]\n");
return1;
}
sub1.value = atoi (argv[1]);
msg.a =&sub1; // Point msg.a to sub1 data
// NOTE: has_b is not required like amessage, thereforecheck for NULL on deserialze
if(argc ==3){ sub2.value = atoi (argv[2]); msg.b =&sub2;}// Point msg.b tosub2 data
len =dmessage__get_packed_size (&msg);// This is the calculatedpacking length
buf = malloc (len); // Allocate memory
dmessage__pack (&msg, buf); // Pack msg, including submessages
fprintf(stderr,"Writing %dserialized bytes\n",len);// See the lengthof message
fwrite (buf, len,1, stdout); // Write to stdout to allow direct command line piping
free(buf);// Free theallocated serialized buffer
return0;
}
Notice:
- there is no has_ flag for optional submessages -- if the pointer is non-NULL, then we assume that it is a value.
- 这里没有submessages的可选项的标识 has_flag---如果指针为非空,则我们假定它是a的值。
下面给出解包代码
#include<stdio.h>
#include"dmessage.pb-c.h"
#define MAX_MSG_SIZE 4096
int main (int argc,constchar* argv[])
{
DMessage*msg; // DMessage using submessages
Submessage*sub1,*sub2;// Submessages
char c;int i=0; // Data holders
uint8_t buf[MAX_MSG_SIZE];// Input datacontainer for bytes
while(fread(&c,1,1,stdin)!=0)
{
if(i >= MAX_MSG_SIZE)
{
fprintf(stderr,"message toolong for allocated buffer\n");
return1;
}
buf[i++]= c;
}
msg = dmessage__unpack(NULL,i,buf);// Deserialize theserialized input
if(msg == NULL)
{// Something failed
fprintf(stderr,"errorunpacking incoming message\n");
return1;
}
sub1 = msg->a; sub2 = msg->b;
printf("Received:a=%d",sub1->value);
if(msg->b != NULL) printf(" b=%d",sub2->value);
printf("\n");
dmessage__free_unpacked(msg,NULL);
return0;
}
命令行中运行,得到结果如下
./dmessage_serialize 45|./dmessage_deserialize
Writing:8 serialized bytes
Received: a=4 b=5
./dmessage_serialize 4|./dmessage_deserialize
Writing:4 serialized bytes
Received: a=4