Is it possible to obtain the string equivalent of protobuf enums in C++?
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);
enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java.
UPDATE 2019: Enums are fine to use in Android since ART replaced DALVIK as runtime environment stackoverflow.com/a/56296746/4213436.
To do this, you need to run the protocol buffer compiler protoc on your . proto : If you haven't installed the compiler, download the package and follow the instructions in the README. Because you want C++ classes, you use the --cpp_out option – similar options are provided for other supported languages.
Enum in java is a data type that contains fixed set of constants. When we required predefined set of values which represents some kind of data, we use ENUM. We always use Enums when a variable can only take one out of a small set of possible values.
The EnumDescriptor and EnumValueDescriptor classes 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.
In this particular case, the following should work (untested):
std::string requestTypeString = MyMessage_RequestType_Name(requestType);
See the answer of Josh Kelley, use the EnumDescriptor and EnumValueDescriptor.
The EnumDescriptor documentation says:
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.
Example, get the protobuf enum:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With