protobuf-c write 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 = 1; | |
addrbook.people = (Tutorial__Person **)malloc(sizeof(Tutorial__Person*) * addrbook.n_people); | |
int index = 0; | |
addrbook.people[index] = (Tutorial__Person *)malloc(sizeof(Tutorial__Person)); | |
tutorial__person__init(addrbook.people[index]); | |
addrbook.people[index]->id = 1; | |
addrbook.people[index]->name = "yoshio"; | |
addrbook.people[index]->email = "yoshio@mail.com"; | |
addrbook.n_people++; | |
addrbook.people = (Tutorial__Person **)realloc(addrbook.people, sizeof(Tutorial__Person*) * addrbook.n_people); | |
index++; | |
addrbook.people[index] = (Tutorial__Person *)malloc(sizeof(Tutorial__Person)); | |
tutorial__person__init(addrbook.people[index]); | |
addrbook.people[index]->id = 1; | |
addrbook.people[index]->name = "yoshida"; | |
addrbook.people[index]->email = "yoshida@mail.com"; | |
uint8_t pad[128]; | |
ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(pad); | |
tutorial__address_book__pack_to_buffer(&addrbook, (ProtobufCBuffer *)&simple); | |
FILE *fp = fopen("addrbook", "wb"); | |
if (fp != NULL) { | |
fwrite(simple.data, simple.len, 1, fp); | |
fclose(fp); | |
} | |
PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple); | |
for (int lp = 0; lp < addrbook.n_people; lp++) { | |
free(addrbook.people[lp]); | |
} | |
free(addrbook.people); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment