Get list of C structure members

前端 未结 6 1780
盖世英雄少女心
盖世英雄少女心 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条回答
  •  -上瘾入骨i
    2020-12-09 18:58

    No, that's not possible.

    C is a statically typed language without reflection. Type names don't have any meaning past the compilation stage, and it's not even the case that any particular variable is at all visible in the binary code. The compiler has a lot of freedom to optimize and reorder, as long as the program behaves as described by the language standard.

    You can try some preprocessor magic to get a limited handle on type names, but that's far from general reflection (and strictly speaking outside the C langauge).

    The principle thing you cannot do in C is this:

    const char * tn = "int";
    auto n = get_type(tn)(42); // a.k.a. "int n = 42;", NOT POSSIBLE
    

    Type names are not runtime concepts; and above that, static typing makes any such construction impossible.

    Here's one of the few preprocessor gimmicks I can think of:

    #define print_size(t) printf("sizeof(" #t ") = %u\n", sizeof(t));
    
    print_size(int);
    print_size(long double);
    

提交回复
热议问题