Hi All
The original idea was posted struct-property name is in char* by matsp
So, to summarize the problem: Suppose you have the following struct
Code:
struct CONFIG {
char *my_val
char *other_val
}
And you have a function that returns one of the two strings of this struct as follows:
Code:
char* function get_config_property(char* prop_name) {
// prop_name contains "my_val" or "other_val"
// -> access propterty using 'prop_name' and return it
}
Below is the code I wrote to accomplish this (using matsp idea):
Code:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* getProperty(char *name ) ;
char* setProperty(char *name, char *value ) ;
struct CONFIG
{
char *abc ;
} *config ;
struct propentry
{
ptrdiff_t offset;
const char *name;
};
#define PE(a) { offsetof(struct CONFIG, a), #a }
struct propentry proptable[] =
{
PE(abc),
//PE(def)
};
int main(void) {
config = (struct CONFIG*)malloc(sizeof(config)) ;
setProperty("abc", "hello") ;
printf("MAIN TEST1, abc=%d\n", config->abc) ;
printf("MAIN TEST2, abc=%d\n", getProperty("abc")) ;
return 0;
}
char* setProperty(char *name, char *value )
{
int i;
for(i = 0; i < sizeof(proptable)/sizeof(proptable[0]); i++)
{
if (strcmp(proptable[i].name, name) == 0)
{
char *ptr = (char *)(((char *)config) + proptable[i].offset);
ptr = value;
}
}
return NULL;
}
char* getProperty(char *name )
{
int i;
for(i = 0; i < sizeof(proptable)/sizeof(proptable[0]); i++)
{
if (strcmp(proptable[i].name, name) == 0)
{
char *ptr = (char *)(((char *)config) + proptable[i].offset);
return ptr;
}
}
return NULL;
}
This code compiles and executes, but doesn't produce the correct output. I have the feeling that I'm very close to the solution, but I probably have to do something with malloc, to initialize the fields of the struct, but where ?
Furthermore, I don't understand the difference between
Code:
char *ptr = (char *)(((char *)config) + proptable[i].offset);
and
Code:
char *ptr = (char *)((config + proptable[i].offset);
I would say the first one is incorrect, but when the struct only contains int properties, everything works fine!
Any comments ?
thnx a lot
LuCa