tags:

views:

121

answers:

3

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!

+1  A: 

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.

unwind
+3  A: 

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;

}
Naveen
I think it's worth pointing out that the "name" (a) here is a compile-time symbol, not something that is being found "at runtime". In the latter case, it would have to be a string, and offsetof() wouldn't work.
unwind
+1  A: 

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.

qrdl