is it possible to execute a function stored as a string? e.g to execute a function in the form:
string str="myFunction()"; -> here i would like to execute "myFunction()"; Thank you!
is it possible to execute a function stored as a string? e.g to execute a function in the form:
string str="myFunction()"; -> here i would like to execute "myFunction()"; Thank you!
You can use the Qt library and QMetaObject::invokeMethod
QMetaObject::invokeMethod( pObject, "myFunction" ); You can do this when the function is exported form some DLL file.
void (*myFunction)(); HMODULE library = LoadLibrary("LIBRARY.DLL"); myFunction = GetProcAddress(library, "myFunction"); myFunction(); FreeLibrary(library); But this is not exactly what you want. Because you don't understand the internals of C++.
No, since C++ is a statically compiled language, this is not directly possible. Function and variable names are (normally) lost during compilation. Apart from using a shared library/DLL, as David suggested, you could also use a std::map and store your functions in it, e.g. (untested):
#include <functional> #include <iostream> #include <unordered_map> // or just <map> void myFunction() { std::cout << "in myFunction\n"; } void anotherFunction() { std::cout << "in anotherFunction\n"; } int main() { std::unordered_map<std::function<void()>> functions; // or just std::map // Store the functions functions["myFunction"] = &myFunction; functions["anotherFunction"] = &anotherFunction; // Call myFunction functions["myFunction"](); // Prints "in myFunction". } As, c.fogelklou already said, the functions must have a compatible prototype; Passing parameters via strings would even require writing a parser.
See also the documentation for std::unordered_map and std::function.
main(), I declared the type of the function as std::function<void()>. If, e.g. your function returns int, you can substitute std::function<int()>.You may also create and embed a language parser, that process and evaluate string you supply.
Further reading: