Search code examples
pythonc++python-c-api

Python embed into C++


I have python codes ebmedded into C++. Do I need to release memory(Py_XDECREF) PyObject* pValue and PyObject *pArgs?

When I do Py_XDECREF(pArgs) and Py_XDECREF(pValue) I have Segmentation Fault (Core dumped). I think python side is still using those variables and c++ try to release memory. What is the best practice for this issue?

for(int i=0; i < 100: i++){
        .......do sth.......
    if (pModule != NULL) {
            std::string st = jps.updateZone(worldx_y, lenVect);                          
            PyObject* pValue = PyBytes_FromString(st.c_str());
            if (pFunc_insert && PyCallable_Check(pFunc_insert)) {
                PyObject *pArgs = PyTuple_New(1);
                PyTuple_SetItem(pArgs, 0, pValue);
                PyObject_CallObject(pFunc_insert, pArgs); 
                Py_XDECREF(pArgs);                               
            } 
            Py_XDECREF(pValue);              
    }
        ......do sth.......

}

Solution

  • PyTuple_SetItem steals a reference to the item. You don't need to decref the item, because you no longer own a reference to it. You do need to decref the tuple.

    If you still get segfaults after that, you have some other bug.