【发布时间】:2018-02-18 15:29:30
【问题描述】:
我在 Linux 设备 (raspberry pi/raspbian) 上使用 Visual Studio 远程调试 c++ 应用程序。在这个 c++ 应用程序中,我通过使用 Python/c api 加载函数来嵌入一个简单的 Python 脚本。这是我的 C++ 代码:
#include <Python.h>
int main(int argc, char* argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyUnicode_FromString("//home//pi//projects//InfoBeam//WebScraperPython.txt");
// 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, "pyMain");
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;
}
问题是,我在运行 PyModule_GetDict(pModule) 函数时遇到了分段错误。我究竟做错了什么?这是错误信息:
程序收到信号SIGSEGV,分段错误。 PyModule_GetDict() 中的 0x76bfdd28 来自 /usr/lib/arm-linux-gnueabihf/libpython3.5m.so.1.0 分段错误
编辑:好的,pModule 确实为 NULL,可能是因为 PyUnicode_FromString 失败。由于 PyImport_Import 失败:我需要在哪里保存我的脚本,或者:我如何将 api 的信息传递给它?
【问题讨论】:
-
我在您的代码中没有看到任何错误检查。
pModule可能为空?还有为什么"//"?与"\\"不同,Is 不是转义序列。无需转义右斜线。
标签: python c++ segmentation-fault python-c-api python-embedding