How to process dynamic source code in C++? Is it possible to use something like eval("foo")?
I have some functions that need to be called depending on user's choice:
void function1 ();
void function2 ();
...
void functionN ();
int main (int argv, char * argv [])
{
char * myString = new char [100];
...
myString = "1" //user input
cout << eval("function"+myString)();
}
How is it usually done?
UPD: Based on slacy's and clinisbut's answers I think I need to make a function registry. I suppose it should be made as an array of pointers to functions. Here's the question, how do I declare an array of pointers to functions?
The real answer to your question is this:
extern "C" {
void function1 ();
void function2 ();
void function3 ();
}
int main (int argv, char * argv [])
{
char * myString = new char [100];
...
myString = "function1"; //user input
void (*f)() = dlsym(RTLD_NEXT, myString);
f();
}
You can obtain the function defined in your binary (by its name, if it was declared with extern "C"), and call it.
On windows, it becomes uglier, but still possible - read on GetProcAddress
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