Reputation: 695
I have a struct containing several members and I need to initialize them from text file. The text file contains values for all members in my struct using the same names. Is there away, to go over all members in the struct and refer to variable name as a string for comparison?
for example:
typedef struct pra_gen_con_file {
int num_of_tasks;
char vsr_id[1000];
} pra_gen_con_file_t;
And in text config file I have:
num_of_tasks = 5
vsr_id = lior
I need something like this:
for line in text_file_lines:
for member in pra_gen_con_file.members():
if member.member_name == line.split('=')[0]:
pra_gen_con_file.member = line.split('=')[1]
I need to implement in C.
Thanks Lior
Upvotes: 0
Views: 994
Reputation:
This kind of introspection capability, though very idiomatic in a language like Python, is impossible in C (without some very strange hacks that will rely on debug information). The compiler typically won't store the names of the variables in the generated binary, so all references to a struct
member are done by adding the offset to the struct
's location in memory
You'll have to parse and assign to the variable names manually.
Take the following C code:
struct my_struct
{
int a;
int b;
float f;
};
void assign(void * a)
{
struct my_struct * m = (struct my_struct*) a;
m->a = 100;
m->b = -10;
m->f = 44.1;
}
On compilation, the compiler actually produces the following assembly (x86_64 Linux, GCC 4.8):
assign:
.LFB20:
.cfi_startproc
movl $100, (%rdi) ;move 100 into the the memory location stored in register %rdi
movl $-10, 4(%rdi); move -10 into (%rdi)+4bytes
movl $0x42306666, 8(%rdi) ;move 44.1(hex representation) into (%rdi)+8 bytes
ret
.cfi_endproc
Upvotes: 2