如何解决';分段错误';C&;python
在我的Ubuntu下: $cat test.py如何解决';分段错误';C&;python,python,c,Python,C,在我的Ubuntu下: $cat test.py #Filename test.py def Hello(): print "Hello, world!" $cat tom.cpp #include <Python.h> int main() { Py_Initialize(); PyObject * pModule = NULL; PyObject * pFunc = NULL; pModule = Py
#Filename test.py
def Hello():
print "Hello, world!"
$cat tom.cpp
#include <Python.h>
int main()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule = PyImport_ImportModule("test");
pFunc = PyObject_GetAttrString(pModule, "Hello");
PyEval_CallObject(pFunc, NULL);
Py_Finalize();
return 0;
}
运行:
美元/年
Segmentation fault
为什么??
有人能帮忙吗?
谢谢
比尔,
Tom前面的海报可能是对的,因此我的评论更“通用”…但是在C/C++中,在尝试引用函数之前,如果不确认函数的指针不为空,就不应该接受它返回的指针。上述准则应更恰当地为:
pModule = PyImport_ImportModule("test");
if (pModule == NULL) {
printf("ERROR importing module");
exit(-1);
}
pFunc = PyObject_GetAttrString(pModule, "Hello");
if (pFunc == NULL) {
printf("ERROR getting Hello attribute");
exit(-1);
}
PyEval_CallObject(pFunc, NULL);
该问题是由
PyObject\u GetAttrString
返回NULL
引起的。我还使用PyRun\u SimpleString
添加了目录路径,因为我的dev dir不在python path下
#包括
int main(){
Py_初始化();
PyRun_SimpleString(“导入sys;sys.path.insert(0,'在此处添加目录路径”);
PyObject*pModule=NULL;
PyObject*pFunc=NULL;
pModule=PyImport_ImportModule(“测试”);
pFunc=PyObject_GetAttrString(pModule,“Hello”);
如果(pFunc!=NULL){
PyEval_CallObject(pFunc,NULL);
Py_Finalize();
}
否则{
printf(“pFunc返回NULL\n”);
}
返回0;
}
@ SniBi首先感谢您的回答,但在正确使用此代码和所有Python和C++文件在同一文件夹中,但我仍然分段故障?你能帮我吗?
pModule = PyImport_ImportModule("test");
if (pModule == NULL) {
printf("ERROR importing module");
exit(-1);
}
pFunc = PyObject_GetAttrString(pModule, "Hello");
if (pFunc == NULL) {
printf("ERROR getting Hello attribute");
exit(-1);
}
PyEval_CallObject(pFunc, NULL);