我正在尝试从我的主C++程序中调用Python脚本中的函数.python函数接受一个字符串作为参数并且不返回任何内容(ok ..'None').只要前一次调用在再次调用函数之前完成,它就可以很好地工作(从未想过会那么容易......),否则就会出现访问冲突pModule = PyImport_Import(pName)
.
有很多教程如何在C中嵌入python,反之亦然,但我没有发现任何关于这个问题.
int callPython(TCHAR* title){
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
Py_Initialize();
pName = PyUnicode_FromString("Main");
/* Name of Pythonfile */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "writeLyricToFile");
/* function name. pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(1);
pValue = PyUnicode_FromWideChar(title, -1);
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
showErrorBox(_T("pValue is false"));
return 1;
}
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
//worked as it should!
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
showErrorBox(_T("pValue is null"));
return 1;
}
}
else {
if (PyErr_Occurred()) PyErr_Print();
showErrorBox(_T("pFunc null or not callable"));
return 1;
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
showErrorBox(_T("pModule is null"));
return 1;
}
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当你说"只要在再次调用函数之前完成上一次调用"时,我只能假设你有多个线程从C++调用到Python.python不是线程安全的,所以这将失败!
阅读Python手册中的全局解释器锁(GIL).也许以下链接将有所帮助:
维基百科上提到了GIL: