mirror of
https://github.com/pybind/pybind11.git
synced 2026-04-20 06:49:25 +00:00
always_construct_holder feature to support intrusively reference-counted types (#561)
* always_construct_holder feature to support intrusively reference-counted types * added testcase
This commit is contained in:
@@ -82,7 +82,11 @@ private:
|
||||
};
|
||||
|
||||
/// Make pybind aware of the ref-counted wrapper type (s)
|
||||
PYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>); // Required for custom holder type
|
||||
|
||||
// ref<T> is a wrapper for 'Object' which uses intrusive reference counting
|
||||
// It is always possible to construct a ref<T> from an Object* pointer without
|
||||
// possible incosistencies, hence the 'true' argument at the end.
|
||||
PYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>, true);
|
||||
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); // Not required any more for std::shared_ptr,
|
||||
// but it should compile without error
|
||||
|
||||
@@ -125,6 +129,18 @@ test_initializer smart_ptr([](py::module &m) {
|
||||
py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj)
|
||||
.def(py::init<int>());
|
||||
|
||||
m.def("test_object1_refcounting",
|
||||
[]() -> bool {
|
||||
ref<MyObject1> o = new MyObject1(0);
|
||||
bool good = o->getRefCount() == 1;
|
||||
py::object o2 = py::cast(o, py::return_value_policy::reference);
|
||||
// always request (partial) ownership for objects with intrusive
|
||||
// reference counting even when using the 'reference' RVP
|
||||
good &= o->getRefCount() == 2;
|
||||
return good;
|
||||
}
|
||||
);
|
||||
|
||||
m.def("make_object_1", &make_object_1);
|
||||
m.def("make_object_2", &make_object_2);
|
||||
m.def("make_myobject1_1", &make_myobject1_1);
|
||||
|
||||
Reference in New Issue
Block a user