Description
pybind11 version is ace4deb
python version is
Python 3.8.6 (default, Sep 30 2020, 04:00:38)
[GCC 10.2.0] on linux
and gcc version is gcc (GCC) 10.2.0
my minimum working example is
#include "/home/hzhangxyz/Desktop/TAT/pybind11/include/pybind11/pybind11.h"
struct A {
int a;
};
struct B {
int *b;
};
namespace py = pybind11;
PYBIND11_MODULE(T, tm) {
py::class_<A>(tm, "A")
.def(py::init<int>())
.def_readonly("a", &A::a)
.def_property_readonly(
"b", [](A &a) { return B{&a.a}; }, py::keep_alive<0, 1>());
py::class_<B>(tm, "B").def_property_readonly("b",
[](const B &b) { return *b.b; });
}
save it as T.cpp
now run g++ T.cpp -I/usr/include/python3.8 -lpython3.8 -fPIC -shared -o T.cpython-38-x86_64-linux-gnu.so
and get T.cpython-38-x86_64-linux-gnu.so
test with python -c 'import T, sys; a=T.A(233); b=a.b; print(sys.getrefcount(a))'
and get output 2
, it is incorrect, it should be 3
so when I do python -c 'import T; a=T.A(233); b=a.b; print(b.b); del a; print(b.b)'
it gives the wrong output
233
279652016
or simply python -c 'import T; print(T.A(233).b.b)'
give incorrect 652495216
Any one can tell me how to let code like T.A(233).b.b
valid?
In my project, I have code like this, the common thing is the def_property_readonly return a object containing the reference(or pointer) to self