How can I call a C++ function from a string?
Instead of doing this, call the method straight from string:
void callfunction(const char* callthis, int []params)
{
if (callthis == "callA")
{
callA();
}
else if (callthis == "callB")
{
callB(params[0], params[1]);
}
else if (callthis == "callC")
{
callC(params[0]);
}
}
In C# we'd use typeof() and then get the method info and call from there... anything we can use 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.
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.
The main function always acts as a driver function and calls other functions. We can also write function call as a parameter to function. In the below code, first add(num1, num2) is evaluated, let the result of this be r1. The add(r1, num3) is evaluated.
Create a std::map made of strings and function pointers. Create the map with all of the functions that you will want to call.
There are other ways to do it, involving symbol tables and dynamic loaders but those ways are not portable or friendly.
Other solutions are variations on the same theme:
switch (callthis)
{
case FUNCA: callA(); break;
case FUNCB: callB(params); break;
... etc.
}
Or search an array of stuctures:
struct {
char *name;
TFunc f;
} funcdefs [] = {
{"callA", callA},
{"callB", callB},
{"callC", callC},
... etc.
{NULL, NULL}
};
for (int j = 0; funcdefs [j] .name; ++j)
if (!strcmp (funcdefs [j] .name, callthis))
{
funcdefs [j] .f (params);
break;
}
You could also look at the answers to How can I add reflection to a C++ application? for information about RTTI, the reflection mechanism in C++.
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With