LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Calling a function from a string

I would like to be able to call a function given the name of the function is in a string. How can I do this?
 
The usage would be something like this:
 
int function_to_call(char parameters[]) {
}
 
void main(void) {
   char function_name[] = "function_to_call";
   char parameter[] = "parameter data"
 
   // I would like to be able to call the function here
 
}
 
 
 
0 Kudos
Message 1 of 4
(3,483 Views)

Unfortunately the function names are not part of the final image of the program, so there's no direct way to translate a string at runtime into a specific function.  However, you can create a static list of function pointers with associated strings something like this:

void FunctionA(void);
void FunctionB(void);

typedef void (*FunctionPtr)(void);
struct FUNCTION_NAMES
{
    FunctionPtr Function;
    char        *FunctionName;
} FunctionList[] =
{
    { FunctionA, "FunctionA" },
    { FunctionB, "FunctionB" }
};

Of course the functions all have to have the same prototype, and you have to manually update the list everytime you add a new function.  You can simplify adding entries to the list by using a macro to define both the function pointer and the string at the same time.

There have been a few times in the last 15 years or so when I considered implementing something like this to solve a specific issue, but each time I finally decided that there was a better way to do what I was trying to do.  The key thing to remember here is that the function names are really just unique identifiers for the compiler and have no contextual meaning what so ever.  Once the program is compiled and running, the function names don't mean anything.  The question you have to ask yourself is why you want to use those function names at run time.  What are you really trying to do?  Can you solve the problem with an enumerated list instead of strings?

Can you provide more details of what you're trying to accomplish?

0 Kudos
Message 2 of 4
(3,480 Views)

Hi Steve.

This thread discusses one possible approach (an embedded script engine). You could also look at Python.

Cheers, Colin.



Message Edited by cdk52 on 05-02-2008 09:05 AM
0 Kudos
Message 3 of 4
(3,459 Views)

If all your functions can be packaged inside a dll then yes, you could use this approach with LoadLibrary() to invoke functions from their string names at runtime.

JR

0 Kudos
Message 4 of 4
(3,362 Views)