gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:48:44 24 4
gpt4 key购买 nike

在下面的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;
}

分机原型(prototype)

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com