user1679802
user1679802

Reputation: 167

execute function stored as a string in c++

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

Answers (7)

hate-engine
hate-engine

Reputation: 2350

You may also create and embed a language parser, that process and evaluate string you supply.

Further reading:

Upvotes: 0

neohope
neohope

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

Oberon
Oberon

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

V-X
V-X

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

spiritwolfform
spiritwolfform

Reputation: 2293

You can use the Qt library and QMetaObject::invokeMethod

QMetaObject::invokeMethod( pObject, "myFunction" );

Upvotes: 0

c.fogelklou
c.fogelklou

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

David Schwartz
David Schwartz

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

Related Questions