c++ - 从 C++ 访问 Protocol Buffer 扩展重复字段

标签 c++ protocol-buffers

在下面的 Protocol Buffer 中,如何从 C++ 访问扩展中的重复字段?

基础.proto

message Base {
    optional int32 id = 1;
    repeated int32 ids = 2;
    optional string name = 3;
    repeated string names = 4;
    extensions 1000 to 1999;    
}

ext.proto

import "base.proto";

extend Base {
    repeated string names = 1000;
    optional int32 number = 1001;
    repeated int32 numbers = 1002;
    optional string name = 1003;
}

以下内容无法编译(在 VS2010 中)

#include "base.pb.h"
#include "ext.pb.h"

using namespace ::google::protobuf;

int main(int argc, char *argv[])
{
    Base b;
    RepeatedPtrField<std::string> base_names = b.names(); // OK
    RepeatedField<int> base_ids = b.ids(); // OK

    int ext_number = b.GetExtension(number); // OK
    std::string ext_name = b.GetExtension(name); // OK
    assert( b.HasExtension(numbers) ); // OK
    assert( b.HasExtension(names) ); // OK
    int32 i = b.GetExtension(numbers); // ? Compiles but doesn't make sense.
    RepeatedField<int32> ext_numbers = b.GetExtension(numbers); // compilation fails:
    RepeatedPtrField<std::string> ext_names = b.GetExtension(names); // compilation fails:
    return 0;
}

编译错误

1>test_proto.cpp(17): error C2440: 'initializing' : cannot convert from 'int' to 'google::protobuf::RepeatedField<Element>'
1>          with
1>          [
1>              Element=google::protobuf::int32
1>          ]
1>          No constructor could take the source type, or constructor overload resolution was ambiguous
1>\test_proto.cpp(18): error C2440: 'initializing' : cannot convert from 'const std::string' to 'google::protobuf::RepeatedPtrField<Element>'
1>          with
1>          [
1>              Element=std::string
1>          ]
1>          No constructor could take the source type, or constructor overload resolution was ambiguous

最佳答案

感谢protobuf上的肖锋邮件列表,使用 ExtensionSize(id) 和 GetExtension(id, index):

Base b;
int index = 0;
if (index < b.ExtensionSize(names))
{
    std::string s_value = b.GetExtension(names, index);
}

关于c++ - 从 C++ 访问 Protocol Buffer 扩展重复字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17358163/

相关文章:

c++ - 模板使用中空 "<>"是什么意思?

c++ - out_of_bounds:基本字符串C++

java - 损坏的 Protocol Buffer 消息

Java 对象类型到 Protobuf

javascript - Protocol Buffer : Uncaught reference error: exports is not defined

go - 在 go 中按顺序将 protobuf 消息写入文件

c++ - C++数据结构的过滤方法

c++ - 进行位移和掩码的最有效/正确的方法是什么?

go - 找不到包 "google/protobuf"

c++ - 嵌套类还是非嵌套类?