仅在对象实例的生存期内使Python解释器保持活动状态 [英] Keeping Python Interpreter Alive Only During the Life of an Object Instance

查看:120
本文介绍了仅在对象实例的生存期内使Python解释器保持活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个使用python解释器的类,如下所示:

I have defined a class for using python interpreter as follows:

class pythonInt
{
public:
    pythonInt(const char* fname) {
        py::initialize_interpreter();
        m_Module = py::module::import(fname);
    }
    ~pythonInt() {
        py::finalize_interpreter();
    }
    py::module m_Module;
    // ... other class members and functions that uses m_Module
};

int main()
{
    pythonInt *p1 = new pythonInt("pybind_test1");
    delete(p1); 

    pythonInt *p2 = new pythonInt("pybind_test1");
    delete(p2); 

    return 0;
}

该类实例被破坏后,我得到 _Py_Dealloc(op)时>访问冲突读取位置错误。如何确定解释器,以便可以成功删除以前创建的类实例 p1 并安全地创建新的类实例 p2

As soon as the class instance is being destructed I get Access violation reading location error when it reaches to deleting the instance _Py_Dealloc(op). How can I finalize the interpreter such that I can successfully delete the previously created class instance p1 and safely create a new class instance p2?

推荐答案

崩溃是b / c数据成员 py :: module m_Module; 是在运行 pythonInt 的构造函数/析构函数之前创建的,并在其运行之后销毁,因此要在初始化之前和解释器完成之后进行。

The crash is b/c the data member py::module m_Module; is created before and destroyed after the constructor/destructor of pythonInt is run, so before initialization and after finalization of the interpreter.

pybind11提供 scoped_interpreter 来满足您的需求,C ++保证访问块中所有数据成员的构造/销毁顺序。因此,假设您将所有(Python)数据放在一起并且 pythonInt 没有基类(带有Python数据成员),则可以选择:

pybind11 offers scoped_interpreter for the purpose you're seeking and C++ guarantees construction/destruction order for all data members in an access block. So, assuming that you keep all (Python) data together and pythonInt has no base class (with Python data members), this would be an option:

#include <pybind11/pybind11.h>
#include <pybind11/embed.h>

namespace py = pybind11;
class pythonInt
{
public:
    pythonInt(const char* fname) {
        m_Module = py::module::import(fname);
    }
    ~pythonInt() {
    }
    py::scoped_interpreter m_guard;
    py::module m_Module;
    // ... other class members and functions that uses m_Module
};

int main()
{
    pythonInt *p1 = new pythonInt("pybind_test1");
    delete(p1);

    pythonInt *p2 = new pythonInt("pybind_test2");
    delete(p2);

    return 0;
}

与您的示例相比,它添加了 #include< ; pybind11 / embed.h> py :: scoped_interpreter m_guard; (再次强调该顺序至关重要);并删除解释器的初始化/完成。

Compared to your example, it adds #include <pybind11/embed.h> and py::scoped_interpreter m_guard; (where again it is to be stressed that the order is crucial); and it removes the interpreter initialization/finalization.

这篇关于仅在对象实例的生存期内使Python解释器保持活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆