How to solve the "lack of segmentation" in hybrid C & Python programming?

Under my 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 = PyImport_ImportModule("test"); pFunc = PyObject_GetAttrString(pModule, "Hello"); PyEval_CallObject(pFunc, NULL); Py_Finalize(); return 0; } 

And then compile it:

 g++ tom.cpp -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7 

Run: $. / A.out

 Segmentation fault 

Why? Can anyone help? Thanks!

BR, Tom

+4
source share
2 answers

The previous poster is probably right, so my comment is more "general" ... but in C / C ++ you should NEVER accept a pointer to a function without confirming it is not NULL before trying to discard it. The code above should be fair:

  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); 
+4
source

The problem is because PyObject_GetAttrString returns NULL. I also added the directory path using PyRun_SimpleString since my dev directory was not under the python path.

 #include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString ("import sys; sys.path.insert(0, 'add the directory path here')"); PyObject * pModule = NULL; PyObject * pFunc = NULL; pModule = PyImport_ImportModule("test"); pFunc = PyObject_GetAttrString(pModule, "Hello"); if(pFunc != NULL) { PyEval_CallObject(pFunc, NULL); Py_Finalize(); } else { printf("pFunc returned NULL\n"); } return 0; } 
+4
source

Source: https://habr.com/ru/post/911430/


All Articles