Get list of C structure members

前端 未结 6 1789
盖世英雄少女心
盖世英雄少女心 2020-12-09 18:07

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

For example, something like this:

struct mystruct {
    int x;
          


        
6条回答
  •  青春惊慌失措
    2020-12-09 19:02

    Take a look at Metaresc library https://github.com/alexanderchuranov/Metaresc

    It provides interface for types declaration that will also generate meta-data for the type. Based on meta-data you can easily serialize/deserialize objects of any complexity. Out of the box you can serialize/deserialize XML, JSON, XDR, Lisp-like notation, C-init notation.

    Here is a simple example:

    #include 
    #include 
    
    #include "metaresc.h"
    
    TYPEDEF_STRUCT (sample_t,
                    int x,
                    float y,
                    string_t z
                    );
    
    int main (int argc, char * argv[])
    {
      mr_td_t * tdp = mr_get_td_by_name ("sample_t");
    
      if (tdp)
        {
          int i;
          for (i = 0; i < tdp->fields_size / sizeof (tdp->fields[0]); ++i)
            printf ("offset [%zd] size %zd field '%s'\n",
                    tdp->fields[i].fdp->offset,
                    tdp->fields[i].fdp->size,
                    tdp->fields[i].fdp->name.str,
                    tdp->fields[i].fdp->type);
        }
      return (EXIT_SUCCESS);
    }
    

    This program will output

    $ ./struct
    offset [0] size 4 field 'x' type 'int'
    offset [4] size 4 field 'y' type 'float'
    offset [8] size 8 field 'z' type 'string_t'
    

    Library works fine for latest gcc and clang.

提交回复
热议问题