Skip to content Skip to sidebar Skip to footer

Keeping Python Interpreter Alive Only During The Life Of An Object Instance

I have defined a class for using python interpreter as follows: class pythonInt { public: pythonInt(const char* fname) { py::initialize_interpreter(); m_Module

Solution 1:

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 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;
classpythonInt
{
public:
    pythonInt(constchar* 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
};

intmain(){
    pythonInt *p1 = newpythonInt("pybind_test1");
    delete(p1);

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

    return0;
}

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.

Post a Comment for "Keeping Python Interpreter Alive Only During The Life Of An Object Instance"