Search code examples
pythonpython-3.xpython-c-api

Python3 C-API: PyObject attributes not exist after passing it to another python function


I am trying to embed a python code as part of my cpp code. So, I impelement the following class to call RunModel in a loop after calling LoadModel:

class PyAdapter {
private:
    PyObject *pModule;
    PyObject *pModel;
    PyObject *pDetectionFunc;
public:
    LoadModel(){
        Py_Initialize();
        ...
        PyObject *pName = PyUnicode_FromString("detection");
        this->pModule = PyImport_Import(pName);
        Py_DECREF(pName);
        ...
        PyObject *pFunc, *pArgs, *pArg;
        pFunc = PyObject_GetAttrString(this->pModule, "model_init");
        pArgs = PyTuple_New(1);
        pArg = PyUnicode_FromString("m1.bin");
        PyTuple_SetItem(pArgs, 0, pArg);
        this->pModel = PyObject_CallObject(pFunc, pArgs);
        Py_DECREF(pArgs);
        Py_DECREF(pFunc);
        ...
        this->pDetectionFunc = PyObject_GetAttrString(this->pModule, "detect_me");
        ...
    }

    RunModel(){
        PyObject *pArgs, *pArg, *pDetection;
        pArgs = PyTuple_New(5);
        PyTuple_SetItem(pArgs, 0, this->pModel);
        ...
        pDetection = PyObject_CallObject(this->pDetectionFunc, pArgs);
        Py_DECREF(pArgs);
        ...
        Py_DECREF(pDetection);
    }

}

after calling the RunModel function for the first time it works properly. However, for the second step it throws:

'XYZ' object has no attribute 'ABC'

to print the pModel object attributes I use the following lines in my Python code:

from pprint import pprint
pprint(vars(MODEL))

for the first step it prints all the expected attributes but for the second step it returns

{}

Please help me understand what's wrong with my code?

EDIT:

I'm not sure which part of the code should be remove or remain. So, i published all the code here: https://pastebin.com/pXhBVbyw and this is test for PyAdapter class.


Solution

  • The problem related to calling Py_DECREF(pArgs) in RunModel function witch destroy all pArgs items (i.e this->pModel). So for the first run it works properly. However after calling Py_DECREF(pArgs) the this->pModel will destroyed and cannot be used for the next runs.