Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to dynamically call a function in c++

Tags:

c++

function

Other than boost (Bind & Function), how can I dynamically call a function in C++?

PHP has:

$obj = new MyObject();
$function = 'doSomething';
$obj->$function();

Objective-C has:

MyObject *obj = [[MyObject alloc] init];
SEL function = NSSelectorFromString(@"doSomething");
[obj performSelector: function];
like image 295
joels Avatar asked Jan 19 '12 05:01

joels


2 Answers

Expanding on Konstantin Oznobihin's answer to the question, you can mark the c++ functions you are referencing with extern "C" in the declaration to prevent the compiler from mangling the names during compilation.

extern "C" void hello() {
    std::cout << "Hello\n";
}

This will allow you to call your object/function by the name you initially gave it. In this case it is 'hello'.

void *handle = dlsym(0, RTLD_LOCAL | RTLD_LAZY);
FunctionType *fptr = (FunctionType *)dlsym(handle, "hello");
fptr();

There are a bunch of things extern "C" does under the hood, so here's a short list: In C++ source, what is the effect of extern "C"?

like image 89
deadbabykitten Avatar answered Oct 18 '22 12:10

deadbabykitten


If I understood your question properly, you can make use of function pointer (or pointer to member) in C++. You can dynamically decide which function call (you may need a prototype of the same) and call it dynamically. See this link

https://isocpp.org/wiki/faq/pointers-to-members

like image 39
sarat Avatar answered Oct 18 '22 12:10

sarat