Search code examples
c++cprotocol-buffersnanopb

How do I get field names and the message name using nanopb in C?


I need the message name and the field name of the protobuf in the form of a string.

I could not find a way to do this in nanopb's documentation.


Solution

  • Nanopb does not have reflection (runtime introspection) support, as listed in features and limitations.

    As such there is no API for accessing or iterating fields by their names.

    At compile time, you can use the FIELDLIST X-macro that is included in the generated .pb.h file. That can be used for autogenerating some things, such as list of strings for the field names.

    The autogenerated list format is:

    #define Person_FIELDLIST(X, a) \
    X(a, STATIC,   REQUIRED, STRING,   name,              1) \
    X(a, STATIC,   REQUIRED, INT32,    id,                2) \
    X(a, STATIC,   OPTIONAL, STRING,   email,             3) \
    X(a, STATIC,   REPEATED, MESSAGE,  phone,             4)
    

    And access is by defining a macro:

    #define STR(x) #x
    #define FIELDNAME_STR(a, atype, htype, ltype, fieldname, tag) STR(fieldname),
    
    const char *fieldnames[] = {
        Person_FIELDLIST(FIELDNAME_STR, 0)
    };
    

    But there is quite little you can actually do with the field names, apart from printing out for logging and similar.