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

void fun1();
voide fun2();
char *fun = "fun1";
(*fun)();

Recommended Answers

All 6 Replies

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 */
(*fptr)(*iptr);

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

commented: good one +1

@nezachem

Brilliant! Did not know that and could be useful!

Thanks N1GHTS, Nezachem and Banfa for your help and ideas.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.