Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve the 'Segmentation fault' when hybrid programming of C & Python?

Tags:

python

c

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? Could anyone help? Thanks!

BR, Tom

like image 617
user866735 Avatar asked Dec 16 '22 02:12

user866735


1 Answers

The previous poster is probably right, so my comment is more "generic"...but in C/C++, you should NEVER accept a pointer back from a function without confirming it's not NULL before attempting to de-refence it. The above code should more rightly be:

 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); 
like image 167
user590028 Avatar answered Jan 26 '23 00:01

user590028