user2856623
user2856623

Reputation: 33

Repeated objects in protobuffers - c

Im having difficulties with sending repeated objects with protobuffers in c. I have declared object im trying to send like so

message IfconfigCfg {
    repeated string name        = 1; 
}

and i am trying to populate in C like this

        ifconfig_cfg.n_name = 2;
        ifconfig_cfg.name = (char*)malloc ( 4 );
        strcpy (ifconfig_cfg.name[0], "la\0");
        strcpy (ifconfig_cfg.name[1], "bc\0");

but im getting inconsistent results and i cant find any good reference about it for C implementation. Can anyone help me please. It would be greatly appreciated. Regards, Blaz I

Upvotes: 0

Views: 1087

Answers (1)

Thomas
Thomas

Reputation: 182083

There is an example in the documentation that does almost exactly what you're after:

message DMessage {
  repeated string d=1;
}
  DMessage msg = DMESSAGE__INIT;  // DMessage (repeated string)
  void *buf;                      // Buffer to store serialized data
  unsigned len,i,j;               // Length of serialized data

  msg.n_d = argc - 1;                      // Save number of repeated strings
  msg.d = malloc (sizeof (char*) * msg.n_d);   // Allocate memory to store strings
  for (j = 0; j < msg.n_d; j++) {
      msg.d[j] = (char*)argv[j+1];         // Access msg.c[] as array
  }
  len = dmessage__get_packed_size (&msg);  // This is calculated packing length
  buf = malloc (len);                      // Allocate required serialized buffer length
  dmessage__pack (&msg, buf);              // Pack the data

Adapted to your case:

        ifconfig_cfg.n_name = 2;
        ifconfig_cfg.name = malloc(sizeof(char*) * ifconfig_cfg.n_name);
        ifconfig_cfg.name[0] = "la";
        ifconfig_cfg.name[1] = "bc";

I suggest you read up on how strings and pointers work in C, because your original code was trying to copy strings into unallocated memory and had needless extra null terminators.

Upvotes: 1

Related Questions