简体   繁体   中英

How to assign address of function pointer according to char*?

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

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 /* ... */

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM