Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Function From a String With the Function’s Name in C++

Tags:

c++

c#

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++?

like image 850
ticpete Avatar asked Nov 28 '09 03:11

ticpete


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 by name as a string?

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 from a function in C?

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.


3 Answers

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.

like image 130
Zan Lynx Avatar answered Sep 30 '22 19:09

Zan Lynx


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;
    }
like image 29
wallyk Avatar answered Sep 30 '22 19:09

wallyk


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.

like image 37
Chip Uni Avatar answered Sep 30 '22 18:09

Chip Uni