2013-06-28 38 views
2

在以下協議緩衝區中,如何從C++訪問擴展中的重複字段?從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 
不編譯
+0

這真的是C++ ??? –

+0

編譯器說什麼? – prehistoricpenguin

+0

您確實記得要將消息def文件標準化以使您生成的消息標題正確嗎? – g19fanatic

回答

3

由於封校的protobuf郵件列表上,使用ExtensionSize(ID)和GetExtension(ID,索引):

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