创建一个cmessage.proto 文件:
message CMessage
{
repeated int32 c=1;
}
源代码生成的方法请参考 《protobuf的C简单的代码例子(一)》
下面给出打包代码:
#include<stdio.h>
#include<stdlib.h>
#include"cmessage.pb-c.h"
int main (int argc,constchar* argv[])
{
CMessage msg = CMESSAGE__INIT; // CMessage(repeated int32)
void*buf; // Buffer to storeserialized data
unsigned len,i; // Length of serialized data
msg.n_c = argc -1; // Save number ofrepeated int32
msg.c = malloc (sizeof(int)* msg.n_c);// Allocate memoryto store int32
for(i =0; i < msg.n_c; i++)
msg.c[i]= atoi (argv[i+1]); // Access msg.c[] as array
len =cmessage__get_packed_size (&msg); // This iscalculated packing length
buf = malloc (len); // Allocaterequired serialized buffer length
cmessage__pack (&msg, buf); // Pack the data
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 (msg.c);// Free storage forrepeated int32
free (buf); // Free serializedbuffer
return0;
}
注意
- 使用 C_MESSAGE__INIT宏创建信息架构
- the n_XXX member is generated for a repeated field XXX.
- n_XXX 成员是通过复域XXX(可简单理解为类似数组的结构)产生的。
下面给出解包的代码
#include<stdio.h>
#include"cmessage.pb-c.h"
#define MAX_MSG_SIZE 4096
int main (int argc,constchar* argv[])
{
CMessage*msg;
uint8_t buf[MAX_MSG_SIZE];
size_t msg_len = read_buffer (MAX_MSG_SIZE, buf);
msg = cmessage__unpack (NULL, len, buf);// Deserialize theserialized input
if(msg == NULL)
{// Something failed
fprintf(stderr,"errorunpacking incoming message\n");
return1;
}
for(i =0; i < msg->n_c; i++)
{// Iterate through all repeated int32
if(i >0)
printf (", ");
printf ("%d", msg->c[i]);
}
printf ("\n");
cmessage__free_unpacked(msg,NULL);// Free the messagefrom unpack()
return0;
}
$ ./cmessage_serialize 12 3 4|./ cmessage_deserialize --->管道命令
Writing:6 serialized bytes ---->打印信息
12,3,4 ---->打印信息