要解决的问题:
在c++中嵌入python解释器,可以执行python脚本,且可以开启多个c++线程来并行执行python脚本。分别使用python的CAPI和结合pybind11 来使用。
测试环境:
Deepin 15.11 / Ubuntu 16.04
python3.5
如果使用Python CAPI, 代码如下 EmbedPyInCpp.cpp
#include <Python.h>
#include <thread>
#include <memory>
void Test()
{
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
const char *filename = "Embed.py";
FILE *f;
f = fopen(filename, "r");
PyRun_SimpleFile(f, filename);
// PyObject *pdict = PyDict_New();
// PyObject *pkey = PyBytes_FromString("app");
// PyObject *pvalue = Py_BuildValue("l", 3);
// PyDict_SetItem(pdict, pkey, pvalue);
// long v = PyLong_AsLong(PyDict_GetItem(pdict, pkey));
// printf("value: %d\n", v);
fclose(f);
PyGILState_Release(gstate);
}
struct Interpre