C++ 如何将protobuf枚举作为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32161409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get protobuf enum as string?
提问by Alexandru Irimiea
Is it possible to obtain the string equivalent of protobuf enums in C++?
是否可以在 C++ 中获得与 protobuf 枚举等效的字符串?
e.g.:
例如:
The following is the message description:
以下是消息说明:
package MyPackage;
message MyMessage
{
enum RequestType
{
Login = 0;
Logout = 1;
}
optional RequestType requestType = 1;
}
In my code I wish to do something like this:
在我的代码中,我希望做这样的事情:
MyMessage::RequestType requestType = MyMessage::RequestType::Login;
// requestTypeString will be "Login"
std::string requestTypeString = ProtobufEnumToString(requestType);
采纳答案by Josh Kelley
The EnumDescriptorand EnumValueDescriptorclasses can be used for this kind of manipulation, and the
the generated .pb.h
and .pb.cc
names are easy enough to read, so you can look through them to get details on the functions they offer.
该EnumDescriptor和EnumValueDescriptor类可用于这种操纵的,而所产生的.pb.h
和.pb.cc
名字是很容易的阅读,所以你可以看看通过他们得到他们所提供的功能的详细信息。
In this particular case, the following should work (untested):
在这种特殊情况下,以下应该有效(未经测试):
std::string requestTypeString = MyMessage_RequestType_Name(requestType);
回答by rmldts
See the answer of Josh Kelley, use the EnumDescriptorand EnumValueDescriptor.
请参阅Josh Kelley的答案,使用EnumDescriptor和EnumValueDescriptor。
The EnumDescriptor documentation says:
EnumDescriptor 文档说:
To get a EnumDescriptor
To get the EnumDescriptor for a generated enum type, call TypeName_descriptor(). Use DescriptorPool to construct your own descriptors.
To get the string value, use FindValueByNumber(int number)
const EnumValueDescriptor * EnumDescriptor::FindValueByNumber(int number) const
Looks up a value by number.
Returns NULL if no such value exists. If multiple values have this >number,the first one defined is returned.
获取 EnumDescriptor
要获取生成的枚举类型的 EnumDescriptor,请调用 TypeName_descriptor()。使用 DescriptorPool 构建您自己的描述符。
要获取字符串值,请使用 FindValueByNumber(int number)
const EnumValueDescriptor * EnumDescriptor::FindValueByNumber(int number) const
按数字查找值。
如果不存在这样的值,则返回 NULL。如果多个值具有此>编号,则返回第一个定义的值。
Example, get the protobuf enum:
例如,获取 protobuf 枚举:
enum UserStatus {
AWAY = 0;
ONLINE = 1;
OFFLINE = 2;
}
The code to read the string name from a value and the value from a string name:
从值中读取字符串名称和从字符串名称中读取值的代码:
const google::protobuf::EnumDescriptor *descriptor = UserStatus_descriptor();
std::string name = descriptor->FindValueByNumber(UserStatus::ONLINE)->name();
int number = descriptor->FindValueByName("ONLINE")->number();
std::cout << "Enum name: " << name << std::endl;
std::cout << "Enum number: " << number << std::endl;