Search code examples
pythonc++python-3.xpython-exec

c++ version of python's exec() functions


objective: executing a string of c(++) code with some kind of function comparable to the exec() function in python.

example in python:

exec('print("hello world")')
#out:
#hello world

question:

is there a c++ version of exec in python?


Solution

  • Well, technicall, you (maybe) can. But it's hardly a justifiable effort, there are other scripting languages that can be integrated in C++. For example Lua. Just to think about it, the following could work, if you have a method int excuteCode(std::string code)

    1. Copy that string into a template that wraps it in some function. The following is an idea of such a template:
    int userFunc()
    {
        %code%
    }
    
    1. Write the template to a file
    2. Build a dynamic library (e.g. a .dll on windows) from that file (call compiler and linker via system or OS-specific methods)
    3. Load the dynamic library into your running program (again, OS-specific methods)
    4. Load the required method userFunc and execute it.