Steve Mucci
Steve Mucci

Reputation: 250

How can one execute C++ code at runtime from a string representing a function?

I'm working on a project wherein I need to be able to save a function string to disk, so I am having the user pass a string of characters that is the actual code of the function and saving it to disk. The opposite is necessary as well; loading a string (from file) and executing as a function at runtime within C++. I need to load this function and return a function pointer to be used in my program. I'm looking at Clang right now, but some of it is a little over my head. So basically I have two questions;

  1. Can Clang run code extracted from a string (loaded from disk)?

  2. Can a compiled Clang function be represented with a function pointer pointing to it?

Any ideas?

Upvotes: 3

Views: 1333

Answers (2)

SoronelHaetir
SoronelHaetir

Reputation: 15172

The simple answer to your question is "yes", the slightly more complex answer is "not at all easily".

Doing it with C++ would require that you compile and link your function into a DLL/shared object, load it, then acquire the exported function. In addition, accepting such code from the user would be a terrible security risk

C++ is a very poor choice for such run-time execution, you would be far better off going with a language meant for that use, JavaScript or Python come to mind.

Upvotes: 8

Robert Columbia
Robert Columbia

Reputation: 6418

You can't easily do this in a compiled language.

For a compiled program to execute a C++ function that has been dynamically provided at runtime, that function would need to be compiled itself. You could make your program call the compiler at runtime to generate a callable library (e.g. one that implements an interface or abstract class and is callable via Dependency Injection), but this is complex and is a project in and of itself. This also means that your application must be packaged with the compiler or must only be installed on systems that contain a compatible compiler - somewhat realistic on Linux, not at all so on Windows.

A better solution would be to use an interpreter. JavaScript and Lisp both come with an eval() function that does exactly what you want - it takes a string (in the case of JavaScript) or a list (in the case of Lisp) and executes it as code.

A third possibility is to find a C++ interpreter that has an eval() function. I'm not sure if any exist. You could try to write one yourself.

Upvotes: 3

Related Questions