From 7e77f5c45be7b232d279c7ec90f3f98bafe3ac07 Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Mon, 16 Sep 2019 04:00:12 -0400 Subject: [PATCH] Add WIP PythonEngine. --- src/PythonEngine.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++ tests/hello.py | 2 ++ 2 files changed, 61 insertions(+) create mode 100644 src/PythonEngine.cpp create mode 100644 tests/hello.py diff --git a/src/PythonEngine.cpp b/src/PythonEngine.cpp new file mode 100644 index 0000000..899c8db --- /dev/null +++ b/src/PythonEngine.cpp @@ -0,0 +1,59 @@ +#include "ScriptEngine.hpp" +#include + + +extern rack::Plugin* pluginInstance; + + +struct PythonEngine : ScriptEngine { + PyInterpreterState* interp = NULL; + + ~PythonEngine() { + if (interp) + PyInterpreterState_Delete(interp); + } + + std::string getEngineName() override { + return "Python"; + } + + int run(const std::string& path, const std::string& script) override { + // Initialize Python + if (!Py_IsInitialized()) { + std::string pythonPath = rack::asset::plugin(pluginInstance, "dep/lib/python3.7"); + wchar_t* pythonPathW = Py_DecodeLocale(pythonPath.c_str(), NULL); + Py_SetPath(pythonPathW); + PyMem_RawFree(pythonPathW); + Py_InitializeEx(0); + + PyEval_InitThreads(); + } + if (!Py_IsInitialized()) { + return -1; + } + + PyThreadState* tstate = PyThreadState_Get(); + interp = PyInterpreterState_New(); + PyThreadState_Swap(tstate); + + if (PyRun_SimpleString(script.c_str())) { + return -1; + } + + // rack::DEBUG("4"); + return 0; + } + + int process() override { + PyThreadState* tstate = PyThreadState_New(interp); + PyEval_RestoreThread(tstate); + PyThreadState_Clear(tstate); + PyThreadState_DeleteCurrent(); + return 0; + } +}; + + +ScriptEngine* createPythonEngine() { + return new PythonEngine; +} \ No newline at end of file diff --git a/tests/hello.py b/tests/hello.py new file mode 100644 index 0000000..eab499c --- /dev/null +++ b/tests/hello.py @@ -0,0 +1,2 @@ + +print("Hello, world!") \ No newline at end of file