execute C++ from String variable

前端 未结 6 920
北恋
北恋 2020-12-01 21:11

it is possible in C++ to execute the C++ code from string variable. Like in Javascript:

var theInstructions = \"alert(\'Hello World\'); var x = 100\";

var F         


        
6条回答
  •  [愿得一人]
    2020-12-01 21:49

    No, C++ is a static typed, compiled to native binary language.

    Although you could use LLVM JIT compilation, compile and link without interrupting the runtime. Should be doable, but it is just not in the domain of C++.

    If you want a scripting engine under C++, you could use for example JS - it is by far the fastest dynamic solution out there. Lua, Python, Ruby are OK as well, but typically slower, which may not be a terrible thing considering you are just using it for scripting.

    For example, in Qt you can do something like:

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QScriptEngine engine;
        QScriptValue value = engine.evaluate("var a = 20; var b = 30; a + b");
    
        cout << value.toNumber();
    
        return a.exec();
    }
    

    And you will get 50 ;)

提交回复
热议问题