Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function named in a string variable in C

Tags:

c

function

I want to call a function using a variable. Is that possible in C?

Actually, what I want to do is, get the function name from the user and store it in a variable. Now I want to call the function that has its name stored. Can anyone tell me how this can be done in C?

I want to develop an AI game engine for a two player game. Two programs with no main function that implement the logic for winning the game will be fed to the game engine. Let me be clear that the program names will be same as that of the primefunctions in the program that implement the logic for winning the game.

So when the user enters the name of first and second players, I can store them in 2 different variables. Now, since the primefunction names are same as that of the program names, I intend to call the functions with variables containing the prog names.

like image 879
wantobegeek Avatar asked Jul 13 '09 10:07

wantobegeek


People also ask

How can I call a function given its name as a string in C?

Put all the functions you want to select from into a dll, then use dlsym (or GetProcAddress on Windows, or whatever other API your system offers) to get the function pointer by name, and call using that.

How do you call a function in a string name?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a function in a string variable?

Use the Variable Method to Call a Function From a String Stored in a Variable in PHP. In PHP, we can also store the functions in variables. The function name should be assigned to a variable as a string, and then we can call the function a variable.

Can I call a function from a string?

You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name]; and now you can use it like a pointer.


1 Answers

C does not support this kind of operation (languages that have reflection would). The best you're going to be able to do is to create a lookup table from function names to function pointers and use that to figure out what function to call. Or you could use a switch statement.

like image 149
Blair Conrad Avatar answered Sep 20 '22 05:09

Blair Conrad