【问题标题】:How to create object from repeated type protobuf如何从重复类型的 protobuf 创建对象
【发布时间】:2019-01-02 14:41:27
【问题描述】:

我要找的是一个返回重复字段消息的函数

我知道 Reflection::AddMessage 具有我想要的返回类型,但我不想添加消息,只需返回该消息的一个对象。

这是我正在尝试做的一个示例,假设我在 .proto 文件中有一条消息:

message Bar{
    uint32 t x = 1;
    uint64 t y = 2;
}

message Foo{
    repeated Bar myMessage = 1;
}

我正在使用反射来遍历 Foo 消息,并且我希望能够执行以下操作:

Message* Msg = createMessage(refl->FooMsg, FieldDesc) 

我知道还有 GetRepeatedMessage 但这需要索引。

【问题讨论】:

    标签: protocol-buffers


    【解决方案1】:

    首先,当 protobuf 编译器生成用于编译的代码时,您会在接口中获得一个访问器函数。函数 mutable_nameOf_message() 返回整个重复字段,它是 c++ 中的 std::vector,或 mutable_nameOf_message( index ),它为您提供指定的元素。

    现在,如果您不想使用 Bar,那么您也不需要。

    message ArrayOfBar 
    {
        repeated Bar arrayOfBar = 0;
    
        message Bar{
            uint32 t x = 1;
            uint64 t y = 2;
        }
    }
    

    如果这就是你的想法,你也可以做这样的事情。

    std::vector<Bar> arrayOfBars;
    

    但由于 Protobuf 的内部细节,这个想法需要改进。类似的事情可能会发生一些不需要的行为。

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 2011-09-15
      • 1970-01-01
      • 2022-08-05
      • 2021-06-04
      • 1970-01-01
      • 2011-10-22
      • 2012-03-13
      • 1970-01-01
      相关资源
      最近更新 更多