views:

62

answers:

4

Hello everyone!

I am writing a C program that could be simplified if I manage to do something like this:

int (*func)(int);
char* str= "adder";
func = str;
func(2);

I create a function pointer, a char*, and I try to assign the name of the function to the pointer through that char*. In this example, the adder(int) function exists.

Is this actually possible?

I know the standard way of doing it would just be func = adder;, but that will not solve it.

Thanks a lot!

Antonio

+2  A: 

That doesn't do what I think you think it should do. If you managed to converted "adder" into a function pointer, you'd be trying to execute the actual text as a function, not what you want. You can keep arrays of function pointers, you can also keep a mapping of text → function pointer. Beyond that, we need more info about what you're doing.

Thanatos
I was actually trying to call a function depending on the arguments passed to the program, without checking the different possibilities with a switch structure
abmirayo
+2  A: 

The best way I know is to put your function in a dynamic library and use dlsym or your operating system's equivalent to get your function pointer. Alternately, you would have to set up your own map from string to function pointer somehow.

Karl Bielefeldt
Thanks for your answer, I will look into setting up a map
abmirayo
+1  A: 

You can accomplish something like this using dlls in windows and the getprocaddress function but you will have to use only functions that have the same signature or keep some type of elaborate mapping. What you are trying to do however requires additional infrastructure. If your using c++ you could use a map to store a relationship between strings and fnptrs.

rerun
Thanks for your answer, but I'm programming in plain C, in UNIX
abmirayo
+2  A: 

You make a table like this:

static const struct {
    char *name;
    int (*func)(int);
} map[] = {
    { "adder", adder },
    /* ... */
    { 0, 0 }
}

And then use this code:

for (i=0; map[i].name && strcmp(map[i].name, str); i++);
if (map[i].func) y = map[i].func(x);
else /* ... */
R..
Thanks a lot for your answer, I think that leads me in the right direction
abmirayo