Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic source code in C++ [closed]

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?

like image 804
Alex Avatar asked Nov 26 '22 20:11

Alex


1 Answers

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

like image 96
alamar Avatar answered Dec 10 '22 11:12

alamar