简体   繁体   English

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

[英]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. 我正在尝试将python代码嵌入到我的cpp代码中。 So, I impelement the following class to call RunModel in a loop after calling LoadModel : 因此,在调用LoadModel之后,我将RunModel以下类在循环中调用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. 首次调用RunModel函数后,它可以正常工作。 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: 要打印pModel对象的属性,我在Python代码中使用了以下几行:

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. 因此,我在这里发布了所有代码: https : PyAdapter是对PyAdapter类的测试。

The problem related to calling Py_DECREF(pArgs) in RunModel function witch destroy all pArgs items (ie this->pModel ). 与在RunModel函数中调用Py_DECREF(pArgs)有关的问题是销毁所有pArgs项(即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. 但是,在调用Py_DECREF(pArgs)this->pModel将被破坏,不能用于下一次运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM