Simple complete example
A simple file,amessage.protofile following the language guide:
message AMessage
{
required int32 a=1;
optional int32 b=2;
}
Generate .h and .c files from the command-line in your current working directory:
protoc-c --c_out=. amessage.proto
Serialize/pack the AMessage as follows:
#include
#include
#include "amessage.pb-c.h"
int main (int argc, const char * argv[])
{
AMessage msg = AMESSAGE__INIT; // AMessage
void *buf; // Buffer to store serialized data
unsigned len; // Length of serialized data
if (argc != 2 && argc != 3)
{ // Allow one or two integers
fprintf(stderr,"usage: amessage a [b]\n");
return 1;
}
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 %d serialized bytes\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
return 0;
}
I left most error handling out for brevity. Notice:
the use of
the A_MESSAGE__INIT macro to construct the message
the has_b member corresponds to the optional b field -- required fields do not have a has_ member.
amessage__get_packed_size returns the length of the packed data.
a_message__pack serializes the message.
On the other hand, to deserialize/unpack a message, try code like this:
#include
#include
#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 message length exceeded\n");
exit(1);
}
}
return cur_len;
}
int main (int argc, const char * argv[])
{
AMessage *msg;</