5

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

user866735
  • 89
  • 2
  • 4

2 Answers2

7

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); 
user590028
  • 11,364
  • 3
  • 40
  • 57
7

The issue is caused by PyObject_GetAttrString returning NULL. I have also added the directory path using PyRun_SimpleString as my dev dir was not under 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;
}
William Miller
  • 9,839
  • 3
  • 25
  • 46
snibu
  • 581
  • 4
  • 16
  • @snibu first thank for your answare but in exactly use this code and all python and c++ files in a same folder but i still segment fault ? do you can help me ? – keyvan vafaee Aug 30 '17 at 21:36