protobuf-c 中repeated类型处理

github上的代码执行不过,修改之:

proto文件:【emessage.proto】

syntax="proto2";
message Submessage {
  required int32 value=1;
}
message EMessage {
  repeated Submessage a=1;
}

 

打包文件:【emessage_serialize.c】

#include 
#include 
#include "emessage.pb-c.h"
int main (int argc, const char * argv[]) 
{
  Submessage **subs;
  void *buf;
  unsigned len,i;
  EMessage msg = EMESSAGE__INIT;
  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 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
  for (i = 1; i < argc; i++)
    free (subs[i]);
  free (subs); 
  return 0;
}

 

解包文件:【emessage_deserialize.c】

#include 
#include "emessage.pb-c.h"
#define MAX_MSG_SIZE 4096
int main (int argc, const char * argv[]) 
{
    EMessage *msg;
    char c; int i=0;
    uint8_t buf[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 allocated buffer\n");
            return 1;
        }
        buf[i++] = c;
    }
    
    msg = emessage__unpack(NULL,i,buf); // Deserialize the serialized input
    if (msg == NULL)
    {
        fprintf(stderr,"error unpacking incoming message\n");
        return 1;
    }
    for (i = 0; i < msg->n_a; i++)
       printf ("%d\n", msg->a[i]->value);
    
    emessage__free_unpacked(msg,NULL);
    
    return 0;
}

 

执行:

./emessage_serialize 4 5 | ./emessage_deserialize

 

结果:

Writing: 8 serialized bytes
4
5

 

你可能感兴趣的:(leprotobuf-)