The C faqs explain it in a way, here is the link.
But I can't understand it, Somebody can explain it for me? Or give me another way?
Thanks so much!
The C faqs explain it in a way, here is the link.
But I can't understand it, Somebody can explain it for me? Or give me another way?
Thanks so much!
You can't, not without implementing some kind of name lookup yourself.
C doesn't have any time of name information left when the program is running.
Supporting this generally for different struct field types is complicated.
I think this example makes the answer clear:
struct test
{
int b;
int a;
};
int main()
{
test t;
test* structp = &t;
//Find the byte offset of 'a' within the structure
int offsetf = offsetof(test, a);
//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;
return 0;
}
If you have your binary compiled with debug information, you can use it to lookup names at runtime. For example gcc
(typically) produces debug info in DWARF format, and you can use libdwarf to process it.
In case of DWARF you can find your field in DW_TAG_member
node, DW_AT_data_member_location
attribute will give you the field's offset, same as you get from offsetof()
at compile time.