LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Getting a variable name based on a string. (https://www.linuxquestions.org/questions/programming-9/getting-a-variable-name-based-on-a-string-32236/)

jtshaw 10-08-2002 09:00 AM

Getting a variable name based on a string.
 
I am writting a communications module that takes in two types of commands, "put variablename value" and "get variablename". The commands come in as text in an eithernet packet. What I want to be able to do is get a pointer to variablename using the string from the comm module so I don't have to have a case statement with hundreds of cases. Anyone have any ideas?

John

OH ya... this is C code running on GCC 2.95.3 under Slackware...

bsdjunkie 10-08-2002 10:19 AM

I would use libdnet or libpcap instead of trying to reinvent the wheel in packet capture ;)

llama_meme 10-08-2002 10:24 AM

No easy way to do this in C. You need to associate strings with pointers to the variables whose values they represent. The simplest way of doing this is to have an array:

typedef struct string_var_assoc
{
char *name;
void *value_pointer;
} string_var_assoc_t;

string_var_assoc_t var_array[] = {
{"foo", &foo},
{"bar", &bar},
{NULL, NULL}, /* Null terminator */
};

Now you can write a function to iterate through the array and set the appropriate value, if some of the variables' values have different types you might want to store the type of the value in string_var_assoc_t, so you can cast the (void *) pointer to the correct type.

The typing out of the array can be made a bit easier with a macro:

#define ASSOC(x) {#x, &x}

ASSOC(x) now expands to {"x", &x}

Hope this hgelps a little.

Alex

jtshaw 10-08-2002 10:52 AM

Ya, thanks. That is what I figured, I think so it is somewhat easy to figure out for the next poor sap that has to deal with this code I will just do it the long way with a case statement, at least the variables names will be descriptive.

leed_25 10-08-2002 11:09 AM

I can't help but thing that I am missing something here. This seems too simple: why not use getenv() and putenv() ?

llama_meme 10-08-2002 11:35 AM

1) Programs shouldn't use the external environment for internal storage
2) You could only store ASCII strings, and you'd have to keep converting them

Still, it's a neat idea, might work OK for some things.

Alex

leed_25 10-08-2002 11:47 AM

Ok, well how about some kind of hashing mechanism, then? It would be fast. 'a switch statement with hundreds of cases..' that just sounds so... so ICKY.

llama_meme 10-08-2002 02:06 PM

Yeah hashing is the fastest way - my example was supposed to show the easiest way. But like jtshaw said, the switch statement is the easiest to understand.

Alex


All times are GMT -5. The time now is 02:46 PM.