Can somebody giv开发者_如何学运维e me an example of packing\unpacking message with repeating sub-message in protobuf-c?
Official documentation in empty on this matter.
message B {
required int64 i = 1;
};
message A {
repeated B numbers = 1;
};
A a;
a.ParseFromString(<str>)
for (int i = 0; i < a.numbers_size(); ++i) {
const B& b = a.numbers(i);
printf("%d\n", b.i());
}
proto:
message SubMsg {
bytes value = 1;
}
message MainMsg {
repeated SubMsg msgs = 1;
}
pack (do not forget to free memory (free(...)):
MainMsg mainMsg = { };
main_msg__init(&mainMsg);
SubMsg **subMsgs = calloc(LEN, sizeof(SubMsg*));
for (int i = 0; i < LEN; i++) {
subMsgs[i] = calloc(1, sizeof(SubMsg));
sub_msg__init(subMsgs[i]);
subMsgs[i]->value.data = DATA;
subMsgs[i]->value.len = DATALEN;
}
mainMsg.msgs = subMsgs;
mainMsg.n_msgs = LEN;
...
main_msg__pack(&mainMsg, BUFFER);
unpack (do not forget to free memory (..._free_unpacked(...)):
MainMsg* mainMsg = main_msg__unpack(nullptr, BUFFERLEN, BUFFER);
if (! mainMsg) {
// error
return;
}
SubMsg **subMsgs = mainMsg->msgs;
...
proto:
message A {
optional uint32 key = 1;
optional uint64 value = 2;
}
message B {
repeated A msg = 1;
}
if have optional XXX field, try to set has_XXX true;
B msg;
filebackup__heartbeat_content__init(&msg);
A **subs = (A**)malloc(N * sizeof(A*));
void *buf;
unsigned len,i;
for (int i = 0; i < N; ++i) {
subs[i] = (A*)malloc(sizeof(A));
filebackup__job_status__init(subs[i]);
subs[i]->key = i + 1;
subs[i]->has_key = 1;
subs[i]->value = (i + 1) * 100;
subs[i]->has_value = 1;
}
msg.msg = subs;
msg.n_msg = N;
len = filebackup__heartbeat_content__get_packed_size(&msg);
buf = malloc(len);
filebackup__heartbeat_content__pack(&msg, (uint8_t *)buf);
"Reading A Message" section of Google's C++ tutorial has relevant sample code: http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html
Also, STL's for_each also appears to work OK (syntactic sugar, more-or-less): std::for_each(a.numbers().begin() ,a.numbers().end() ,[](const B& b) { std::cout << b.i() << std::endl ; } ) ;
精彩评论