获取 C 结构成员列表 [英] Get list of C structure members

查看:27
本文介绍了获取 C 结构成员列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将结构的成员列表作为 char ** 获取?

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

例如,像这样:

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 ?

感谢您的宝贵时间.

推荐答案

绝对没有标准的方法.

如果您愿意编译代码两次,您可以只为第二遍启用预处理器定义包装的代码路径,它从第一遍生成的编译单元中读取调试信息以获取成员名称.您还可以分析源代码以在运行时获取列表.

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.

这篇关于获取 C 结构成员列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆