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

前端 未结 2 1570
逝去的感伤
逝去的感伤 2021-01-13 16:37

Under my Ubuntu:

$ cat test.py

#Filename test.py 
def Hello(): 
    print \"Hello, world!\" 

$ cat tom.cpp

#inclu         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 17:17

    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 
    
    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;
    }
    

提交回复
热议问题