gpt4 book ai didi

c++ - 读取 Protocol Buffer 中枚举扩展的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:54 26 4
gpt4 key购买 nike

我刚问了this question并决定在我的 Protocol Buffer 中为枚举值编写一个扩展。然而,即使使用这个简单的 .proto 文件,我也很难真正读回这些值:

package test;

import "google/protobuf/descriptor.proto";

extend google.protobuf.EnumValueOptions {
optional string abbr = 54321;
}

message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType { MOBILE = 0 [(abbr)="Mobile ph"]; HOME = 1 [(abbr)="HomePhone"]; WORK = 2 [(abbr)="Work number"]; }

message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}

repeated PhoneNumber phone = 4;
}

message AddressBook {
repeated Person person = 1;
}

我一直在尝试这些和其他变体:

test::Person::PhoneNumber::descriptor()->options().GetExtension(test::abbr);
test::Person::PhoneNumber::descriptor().GetExtension(test::abbr);
test::Person::descriptor()->options().GetExtension(test::abbr);

const google::protobuf::Descriptor* message = test::Person::PhoneNumber::descriptor();
const google::protobuf::Descriptor* desc = phone2.descriptor();
desc->options().GetExtension(test::abbr); //D.N.E.

google::protobuf::MessageOptions opts = message->options();
opts.GetExtension(test::abbr);

const google::protobuf::EnumDescriptor* enm = message->FindEnumTypeByName("PhoneNumber"); // null, not found
google::protobuf::EnumValueOptions opts2 = enm->value(1)->options();
opts2.GetExtension(test::abbr);

test::Person::PhoneNumber::descriptor()->options().GetExtension(test::abbr);

以上都不起作用 - 该方法根本不存在,或者没有对该函数签名的匹配调用。我已经浏览了几个小时的文档,但无济于事。我知道这应该是可能的,但唯一的例子是编写 .proto 文件,而不是从中读回——我该怎么做?一个简短的例子将不胜感激。提前致谢。

最佳答案

有点复杂,但你需要得到 EnumValueDescriptor电话类型,然后调用 options().GetExtension(test::abbr)

例如:

test::Person person;
person.set_name("Caol Ila");
person.set_id(1);

test::Person::PhoneNumber *phone = person.add_phone();
phone->set_number("01496 840207");
phone->set_type(test::Person::MOBILE);

phone = person.add_phone();
phone->set_number("01496 840207");
phone->set_type(test::Person::HOME);

phone = person.add_phone();
phone->set_number("01496 840207");
phone->set_type(test::Person::WORK);

phone = person.add_phone();
phone->set_number("01496 840207");

const google::protobuf::EnumDescriptor* enum_desc =
test::Person::PhoneType_descriptor();
std::string value;

for (int phone_index = 0; phone_index < person.phone_size(); ++phone_index) {
if (person.phone(phone_index).has_type()) {
int phone_type = person.phone(phone_index).type();
value = enum_desc->value(phone_type)->options().GetExtension(test::abbr);
}
}

关于c++ - 读取 Protocol Buffer 中枚举扩展的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511822/

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