获取C结构成员的列表(Get list of C structure members)

编程入门 行业动态 更新时间:2024-10-28 18:22:06
获取C结构成员的列表(Get list of C structure members)

是否有可能将结构成员的列表作为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.

更多推荐

本文发布于:2023-08-03 03:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1383144.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   结构   列表   members   structure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!