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];
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"?
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
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