问题
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;
}
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
?
回答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;
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;
}
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.
来源:https://stackoverflow.com/questions/60100922/keeping-python-interpreter-alive-only-during-the-life-of-an-object-instance