【发布时间】:2016-08-03 14:09:02
【问题描述】:
我正在尝试将 python 脚本嵌入到 c++ 应用程序中。 为了尝试集成,我做了一个试验代码:
// c++ code
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
if (argc < 3)
{
printf("Usage: exe_name python_source function_name\n");
return 1;
}
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyBytes_FromString(argv[1]);
//std::to_string(argv[1]).encode(
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, argv[2]);
if (PyCallable_Check(pFunc))
{
PyObject_CallObject(pFunc, NULL);
}
else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
# Python script
def multiply():
c = 12345*6789
print ('The result of 12345 x 6789 :' + str(c))
我遇到了建议使用 boost 的帖子。 提升比这更简单吗?简单的定义:更少的代码,直接的,被社区广泛使用。
我对这些问题很感兴趣,因为我们要集成的真实代码非常复杂(因为不遵循编码伦理),并且它需要与 Python 代码多次通信,因此也存在同步问题。
【问题讨论】:
-
崩溃发生在哪里?你如何调用你的程序(即你传递给它的参数是什么)?您的实际代码中是否有任何空指针检查?
-
代码在 `pFunc = PyDict_GetItemString(pDict, argv[2]);` 行崩溃;是的,正在检查指针是否为空,直到 pDict 的每个人都不为空。我这样称呼它:
./test_cpp.o test_python multiplytest_python 是 python 脚本的名称 -
崩溃的调用栈是直接指向这一行,还是python内部的某个地方?坠机的具体情况是什么?
-
本题C++内容不多,c标签可能更合适。