Reputation: 167
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!
Upvotes: 2
Views: 1098
Reputation: 2350
You may also create and embed a language parser, that process and evaluate string you supply.
Further reading:
Upvotes: 0
Reputation: 1832
You'd better try python, ruby or even matlab instead of c++.
But if you insist,you can try to integrate LUA in you project.
It can solve your problem.
Upvotes: 0
Reputation: 3249
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.
Upvotes: 0
Reputation: 3029
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++.
Upvotes: 0
Reputation: 2293
You can use the Qt library and QMetaObject::invokeMethod
QMetaObject::invokeMethod( pObject, "myFunction" );
Upvotes: 0
Reputation: 1801
Apart from what David said, you could also create a mapping where each node contains the name of the function and a pointer to the function. Then look up the node by name in the mapping and call the function pointer. This assumes that all functions have the same prototype.
Upvotes: 2
Reputation: 182753
You would have to compile it into a shared library, load that library, and call into it. It can be done, but it's not pretty. Most likely, there is a good way to do whatever is it you're trying to do.
Upvotes: 2