How can I access the structure fields by name at runtime?

C faqs explain this in a way, here is the link.

But I can’t understand it. Can anyone explain this to me? Or give me another way?

Many thanks!

+3
source share
5 answers

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;

}
+5
source

You cannot, without performing any search by name yourself.

C has no name information left after starting the program.

Supporting this is usually difficult for different types of structure fields.

+1
source

, . , gcc () DWARF, libdwarf .

DWARF DW_TAG_member node, DW_AT_data_member_location , , offsetof() .

+1

, offsetof(). structp , f int offsetf, f

*(int *)((char *)structp + offsetf) = value;
0

struct {...}, , , , - . "" , , , .

, , . , :

#define MAKE_ACME_STRUCT \
  FIELD(id,int,23) \
  X FIELD(name,char30,"Untitled") \
  X FIELD(info,int,19) \
  // LEAVE THIS COMMENT HERE

MAKE_ACME_STRUCT , FIELD X , struct, , , [, -

STRUCT_INFO acme_struct_info[] = {
  {"id", STRUCT_INFO_TYPE_int, sizeof(ACME_STRUCT.id), offsetof(ACME_STRUCT.id)}
  ,{"name", STRUCT_INFO_TYPE_char30, sizeof(ACME_STRUCT.name), offsetof(ACME_STRUCT.name)}
  ,{"info", STRUCT_INFO_TYPE_int, sizeof(ACME_STRUCT.info), offsetof(ACME_STRUCT.info)}
  ,{0}};

, , , STRUCT_INFO_TYPE_nameGoesHere, , .

Such macros are hardly beautiful, but they have the advantage that all the things they use to determine remain synchronous (for example, adding or removing an element acme_structwill add or remove it from the list of structure elements stored in acme_struct_info].

0
source

Source: https://habr.com/ru/post/1738486/


All Articles