How to get protobuf enum as string?

Alexandru Irimiea picture Alexandru Irimiea · Aug 23, 2015 · Viewed 39.1k times · Source

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);

Answer

Josh Kelley picture Josh Kelley · Aug 23, 2015

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);