是否有可能将结构成员的列表作为char ** ?
例如,像这样的东西:
struct mystruct { int x; float y; char *z; }; /* ... */ char **members = MAGIC(struct mystruct); /* {"x", "y", "z", NULL}. */我也对依赖于编译器的方法感兴趣。 有这样的事吗?
感谢您的时间。
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.
最满意答案
绝对没有标准的方法。
如果您愿意两次编译代码,那么只能启用预处理器定义包装的代码路径,以便第二遍读取第一遍生成的编译单元中的调试信息以获取成员名称。 您也可以在运行时分析源代码以获取列表。
最后,可以使用预处理器宏来定义结构,并让宏为每个结构成员在另一个变量中发出一个入口,从而有效地保持两个不直接相关的项同步。
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.
更多推荐
发布评论