Let's asume I have a struct as follows:
struct person {
int age;
char name[24];
} person;
and the user gives an argument which struct member the program should read. ./program age
int main(int argc, char **argv) {
int i;
i = person.argv[1];
printf("%i\n", i);
}
this is obviously not possible in this way. Is there a way to read a struct member without typing the exact member name in code? The only way I could think of is to compare the given string to a string named after each struct member.
C does not support run-time reflection in any way that would make that easy to get to work. I suspect the best you can do is to write a code-generator that writes the string-to-struct member selection function.
The most efficient way to code this, both in terms of typing and run-time performance, is probably to use gperf.
Basically, you type the list of names you want, and what you want that to map to (array index, variable pointer, whatever) and it will generate C code to do that for you.
The only problem is that you have to learn how to use it first.
Here's an example from some real-world code: conf.c confitems.gperf
Note that the gperf file maps a string to a C macro so the programmer can put whatever they like inside that macro, and even use it for different purposes in different places. The C file then includes the generated code, and call the generated function confitems_get to do the mapping: string in, macro contents out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With