protobuf-c中重复的子消息

zysjyyx4  于 2022-12-17  发布在  其他
关注(0)|答案(4)|浏览(114)

有人能给予我一个在protobuf-c中使用重复子消息打包/解包消息的示例吗?
empty中关于此问题的官方文档。

mgdq6dx1

mgdq6dx11#

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());
}
zpf6vheq

zpf6vheq2#

原型:

message SubMsg {
  bytes value = 1;
}

message MainMsg {
  repeated SubMsg msgs = 1;
}

pack(不要忘记释放内存(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);

解压缩(不要忘记释放内存(..._free_unpacked(...)):

MainMsg* mainMsg = main_msg__unpack(nullptr, BUFFERLEN, BUFFER);
if (! mainMsg) {
    // error
    return;
}

SubMsg **subMsgs = mainMsg->msgs;
...
xmd2e60i

xmd2e60i3#

原型:

message A {
  optional uint32 key = 1;
  optional uint64 value = 2;
}

message B {
  repeated A msg = 1;
}

如果有可选XXX字段,请尝试将has_XXX设置为真;

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);
xtfmy6hx

xtfmy6hx4#

Google的C++教程中的“阅读消息”部分有相关的示例代码:http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html
此外,STL的for_each看起来也工作正常(语法糖,或多或少):标准::for_each(a.数字().开始(),a.数字().结束(),[](常量B和b){标准::cout〈〈b.i()〈〈标准::endl ;);

相关问题