in

pybind11 class method return pointer runtime failed


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:

  1. delete the delete m_a in destructor, then script work well, but I think this is a not proper way, may cause memory leak
  2. debug pybind11, found that before Exception occure, stop at different place.

It confused me. I can’t figure out what mistake I have made.



Source: https://stackoverflow.com/questions/70538889/pybind11-class-method-return-pointer-runtime-failed

How to resolve codec issues when combining video and audio files in ffmpeg?

A most easily usable improvement rate calculator library in Dart