Hi all
Can we convert a string to function name in c. I am not looking for function pointer.

void fun1();
voide fun2();
char *fun = "fun1";
8 Years
Discussion Span
Last Post by sundip

You can't do that. The best you can do is have an array of structures containing the names and the appropriate function pointer so you can look up the name in the array and then call the associated function pointer.


That is true. But I like in other way. I have tried to convert a string to class and it is working. but now i required to convert string to function.


I can't think of any library function that could do this, but you can always put these named functions into a shared library and use something like dlsym() and access them with a string containing the function name.

Shown here is an example. It shows you how you can also access structures and variables using strings as well as functions.

void    *handle;
int     *iptr, (*fptr)(int);

/* open the needed object */
handle = dlopen("/usr/home/me/libfoo.so", RTLD_LOCAL | RTLD_LAZY);

/* find the address of function and data objects */
*(void **)(&fptr) = dlsym(handle, "my_function");
iptr = (int *)dlsym(handle, "my_object");

/* invoke function, passing value of integer as a parameter */

Edited by N1GHTS: n/a


A separate dll is not necessary. dlopen(0, ...) gives a handle to the main module.

Votes + Comments
good one
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.