简体   繁体   中英

Finding the elements in a structure in C language

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?

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 says

a = mystruct.y

in 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.

No, it isn't possible. C has no inbuilt reflection-style support.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM