joels
joels

Reputation: 7711

how to dynamically call a function in c++

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

Upvotes: 12

Views: 13036

Answers (5)

sarat
sarat

Reputation: 11120

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

Upvotes: 4

deadbabykitten
deadbabykitten

Reputation: 169

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

Upvotes: 4

Konstantin Oznobihin
Konstantin Oznobihin

Reputation: 5327

You can export necessary functions (e.g by marking them with __dllexport) and use GetProcAddress or dlsym (depending on your platform) for getting their address:


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


HANDLE handle = GetCurrentProcess();
FunctionType *fptr = (FunctionType *)GetProcAddress(handle, "doSomething");
fptr();

All of this is platform-specific though and there is no standard way in C++ for doing this.

Upvotes: 10

Graham Perks
Graham Perks

Reputation: 23390

The simple answer is, you can't. C++ doesn't do method look up by name.

Upvotes: 2

stralep
stralep

Reputation: 1008

If those functions you are interested in are of same type, you could create map of strings and function pointers.

Upvotes: 2

Related Questions