【问题标题】:Iterate over all the fields and get their values in protobuf message遍历所有字段并在 protobuf 消息中获取它们的值
【发布时间】:2014-12-29 11:55:47
【问题描述】:

我有一条动态的protobuf 消息,但我不知道该消息包含哪些字段。

我要做的是,把所有字段的所有值都放到一个字符串中,例如消息包含string name = "Jack";int age = 12;两个字段,我想要的最终结果是"name:Jack, age:12"

这是我的想法,由于我不知道这条消息中包含哪些字段,所以我需要遍历消息获取所有字段的名称、类型(可以通过Descriptor访问),然后获取每个字段的值,这是最烦人的部分,因为我需要写很长的

switch (type) {
case TYPE_UINT32:
    //call get_uint32
    break;
case TYPE_UINT64:
    //call get_uint64
    break;
......
}

我想知道有没有其他更好的办法来做到这一点?

【问题讨论】:

标签: c++ protocol-buffers


【解决方案1】:

这基本上就是 Protobuf 自己的 TextFormat 类所做的:

https://github.com/google/protobuf/blob/master/src/google/protobuf/text_format.cc#L1473

您可以在编写自己的代码时使用该代码作为示例。确实比较繁琐,但是真的没有更好的办法了。

【讨论】:

    【解决方案2】:
    Message* message = &your_proto;
    const google::protobuf::Descriptor* desc = message->GetDescriptor();
    const google::protobuf::Reflection* ref = message->GetReflection();
    for (int i = 0; i < desc->field_count(); ++i) {
      const google::protobuf::FieldDescriptor* field_desc = desc->field(i); 
      switch (field_desc->cpp_type()) {
        case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
          // call get_int32
          break;
        case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
          // call get_int64
          break;
        ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多