Reputation: 655
Suppose in the source code, I define a static function void MyFun(void)
. Then I put a string "void MyFun(void)"
in a configuration file. At runtime, I want to load the configuration file to get the string and then create/bind a function-pointer to the corresponding static function. Is it possible to do such a thing (I understand C++ doesn't have reflection)?
Upvotes: 1
Views: 207
Reputation: 1581
Another option besides maintaining a map is to compile your code into a shared library and use OS API to lazy load symbols. This is ABI-depended solution though and in C++ you should be aware of name mangling or use extern "C" for function declaration. The POSIX C example is taken from https://rosettacode.org/wiki/Call_a_function_in_a_shared_library#C
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main()
{
void *mylib;
int (*myfun)(const char *);
mylib = dlopen("./mylib.so", RTLD_LAZY);
*(void **)(&myfun) = dlsym(mylib, "MyFun");
/* ... */
if (mylib) dlclose(mylib);
return EXIT_SUCCESS;
}
Upvotes: 2