I tried a simple pybind11 example, like this:
// header
class Test
{
private:
int* m_a;
public:
Test(int a);
~Test();
int* getA();
};
// cpp
Test::Test(int a){ m_a = new int(a); }
Test::~Test(){ delete m_a; }
int* Test::getA(){ return m_a; }
// bind
namespace py = pybind11;
PYBIND11_MODULE(bindtestlib, m)
{
py::class_<Test>(m, "Test")
.def(py::init<int>())
// as offical guide said, use policy refercence if return bare pointer
.def("getA", &Test::getA, py::return_value_policy::reference);
}
then import this model in python script
import bindtestlib as bt
t = bt.Test(2)
a = t.getA()
print(a)
run this script will print a
's value correctly, but encounter a error before exit
pig
then stuck without exit
I tried two ways:
- delete the
delete m_a
in destructor, then script work well, but I think this is a not proper way, may cause memory leak - debug pybind11, found that before Exception occure, stop at different place.
It confused me. I can't figure out what mistake I have made.