creflectionstruct

Get list of C structure members


Is it possible to get the list of members of a structure as a char ** ?

For example, something like this:

struct mystruct {
    int x;
    float y;
    char *z;
};

/* ... */

char **members = MAGIC(struct mystruct); /* {"x", "y", "z", NULL}. */

I am also interested in compiler-dependent methods. Is there such a thing ?

Thank you for your time.


Solution

  • There's definitely no standard way.

    If you're willing to compile the code twice, you could have a preprocessor-define-wrapped codepath only enabled for the second pass which reads debugging information from the compilation units produced by the first pass to get the member names. You could also analyze the source code to get the list at run time.

    Finally, you could use preprocessor macros to define the struct and have the macros also emit an entry in another variable for each struct member, effectively keeping two not-directly-related items in sync.