C语言中查找结构体中的元素
是否可以确定库中结构(C 语言)中的元素(名称和数据类型)?如果可以的话,用C语言怎么实现呢?如果C语言不支持,是否可以通过其他技巧获取结构元素或者有没有工具?
Is it possible to determine the elements(name & datatype) in a structure(C language) in a library ? If yes, how to do it in C language ? If C language does not support it, Is it possible to get the structure elements by other tricks or is there any tool for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这是不可能的。 C 没有内置的反射风格支持。
No, it isn't possible. C has no inbuilt reflection-style support.
如果“确定结构的元素”意味着“以编程方式获取该结构类型的声明”,那么我不认为这是可能的 - 至少不能移植。与 C++ 或 Java 等更现代的语言相反,C 并不以实际程序可用的形式保存类型信息。
编辑:
为了澄清我关于它不可能“可移植”的评论:
很可能存在一些编译器+调试格式组合,可以将必要的信息嵌入到它生成的目标文件中,尽管我不能说我知道 之一。然后,假设,您可以让程序打开自己的可执行文件并解析调试信息。但这是一种麻烦且脆弱的方法,充其量......
为什么你需要做这样的事情?
If by "determine the elements of a structure" you mean "get the declaration of that structure type programmatically", then I do not believe that it is possible - at least not portably. Contrary to more modern languages like C++ ot Java, C does not keep type information in a form available to the actual program.
EDIT:
To clarify my comment about it being impossible "portably":
There could very well be some compiler+debugging format combination that would embed the necessary information in the object files that it produces, although I can't say I know of one. You could then, hypothetically, have the program open its own executable file and parse the debugging information. But this is a cumbersome and fragile approach, at best...
Why do you need to do something like that?
你的意思是在编程时发现,还是在运行时动态发现?
对于前者,当然。只需找到您所包含的 .h 文件,您就会在那里找到包括所有字段的结构定义。
对于后者来说,不,这是不可能的。 C 将结构编译为机器代码的方式会丢失所有这些信息。例如,如果您有一个 struct
{int x, float y, int z}
,并且您有一些在机器代码中表示的代码,那么剩下的就是找到指向 < 的指针。 code>mystruct,向其中添加 4(int 的大小),并从那里读取 4 个字节,然后对其进行一些浮点运算。这些结构体字段的名称和类型都无法访问,因此无法在运行时找到它们。
Do you mean find out when you are programming, or dynamically at runtime?
For the former, sure. Just find the .h file which you are including and you will find the struct definition there including all the fields.
For the latter, no, it is not possible. C compiles structs to machine code in such a way that all of this information is lost. For example, if you have a struct
{int x, float y, int z}
, and you have some code which saysin the machine code, all that will remain is something like finding the pointer to
mystruct
, adding 4 to it (the size of the int), and reading 4 bytes from there, then doing some floating point operations to it. Neither the names nor the types of those struct fields will be accessible at all, and therefore, there is no way to find them out at runtime.