Python3 C-API: PyObject 属性在传递给另一个 python 函数后不存在

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

我正在尝试嵌入一个 python 代码作为我的 cpp 代码的一部分。因此,我在调用 LoadModel 后执行以下 class 以在循环中调用 RunModel

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

}

在第一次调用 RunModel 函数后,它可以正常工作。但是,对于第二步,它抛出:

'XYZ' object has no attribute 'ABC'

为了打印 pModel 对象属性,我在 Python 代码中使用了以下几行:

from pprint import pprint
pprint(vars(MODEL))

第一步打印所有预期的属性,但第二步打印 returns

{}

请帮助我了解我的代码有什么问题?

编辑:

我不确定应该删除或保留代码的哪一部分。所以,我在这里发布了所有代码:https://pastebin.com/pXhBVbyw and this is test for PyAdapter class.

与在 RunModel 函数 中调用 Py_DECREF(pArgs) 相关的问题销毁所有 pArgs 项(即 this->pModel)。所以对于第一个 运行 它工作正常。但是在调用 Py_DECREF(pArgs) 之后 this->pModel 将被销毁并且不能用于接下来的 运行s。