Call a function named in a string variable in C

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.


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.


The best you can do is something like this:

#include <stdio.h>

// functions
void foo(int i);
void bar(int i);

// function type
typedef void (*FunctionCallback)(int);
FunctionCallback functions[] = {&foo, &bar};

int main(void)
{
    // get function id
    int i = 0;
    scanf("%i", &i);

    // check id
    if( i >= sizeof(functions))
    {
        printf("Invalid function id: %i", i);
        return 1;
    }

    // call function
    functions[i](i);

    return 0;
}

void foo(int i)
{
    printf("In foo() with: %i", i);
}

void bar(int i)
{
    printf("In bar() with: %i", i);
}

This uses numbers instead of strings to identify the functions, but doing it with strings is simply a matter of converting the string into the proper function.

What are you doing, exactly? If just for curiosity, here you go, but if you're trying to solve a problem with this, I'm sure there is a way better suited to your task.

Edit

In concern with your edit, you will want to go with onebyone's answer, for sure.

You want your user's to build dynamic libraries (thats a shared object [.so] in Linux, and a dynamic link library [.dll] in Windows).

Once you do that, if they provide you with the name of their library, you can ask the operating system to load that library for you, and request a pointer to a function within that library.