Skip to content

Instantly share code, notes, and snippets.

@hirokuma
Last active April 1, 2018 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokuma/11fed489bd97fa62daed686dec622646 to your computer and use it in GitHub Desktop.
Save hirokuma/11fed489bd97fa62daed686dec622646 to your computer and use it in GitHub Desktop.
protobuf-c write
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "addressbook.pb-c.h"
int main(int argc, char *argv[])
{
Tutorial__AddressBook addrbook;
uint8_t *buf;
unsigned int len;
tutorial__address_book__init(&addrbook);
addrbook.n_people = 2;
addrbook.people = (Tutorial__Person **)malloc(sizeof(Tutorial__Person*) * addrbook.n_people);
for (int lp = 0; lp < addrbook.n_people; lp++) {
addrbook.people[lp] = (Tutorial__Person *)malloc(sizeof(Tutorial__Person));
tutorial__person__init(addrbook.people[lp]);
}
addrbook.people[0]->id = 1;
addrbook.people[0]->name = "yoshio";
addrbook.people[0]->email = "yoshio@mail.com";
addrbook.people[1]->id = 1;
addrbook.people[1]->name = "yoshida";
addrbook.people[1]->email = "yoshida@mail.com";
len = tutorial__address_book__get_packed_size(&addrbook);
buf = (uint8_t *)malloc(len);
tutorial__address_book__pack(&addrbook, buf);
FILE *fp = fopen("addrbook", "wb");
if (fp != NULL) {
fwrite(buf, len, 1, fp);
fclose(fp);
}
for (int lp = 0; lp < addrbook.n_people; lp++) {
free(addrbook.people[lp]);
}
free(addrbook.people);
free(buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment