从C ++访问协议缓冲区扩展重复字段

时间:2013-06-28 06:00:11

标签: c++ protocol-buffers

在以下协议缓冲区中,如何从C ++访问扩展中的重复字段?

base.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

1 个答案:

答案 0 :(得分:3)

感谢Feng Xiao在protobuf邮件列表上,使用ExtensionSize(id)和GetExtension(id,index):

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