Skip to content

Commit 669d437

Browse files
committed
Attach python lifetime to shared_ptr passed to C++
- Reference cycles are possible as a result, but shared_ptr is already susceptible to this in C++
1 parent 721834b commit 669d437

File tree

3 files changed

+110
-1
lines changed

3 files changed

+110
-1
lines changed

include/pybind11/cast.h

+34-1
Original file line numberDiff line numberDiff line change
@@ -1524,6 +1524,39 @@ struct holder_helper {
15241524
static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
15251525
};
15261526

1527+
/// Another helper class for holders that helps construct derivative holders from
1528+
/// the original holder
1529+
template <typename T>
1530+
struct holder_retriever {
1531+
static auto get_derivative_holder(const value_and_holder &v_h) -> decltype(v_h.template holder<T>()) {
1532+
return v_h.template holder<T>();
1533+
}
1534+
};
1535+
1536+
template <typename T>
1537+
struct holder_retriever<std::shared_ptr<T>> {
1538+
struct shared_ptr_deleter {
1539+
// Note: deleter destructor fails on MSVC 2015 and GCC 4.8, so we manually
1540+
// call dec_ref here instead
1541+
handle ref;
1542+
void operator()(T *) { ref.dec_ref(); }
1543+
};
1544+
1545+
static auto get_derivative_holder(const value_and_holder &v_h) -> std::shared_ptr<T> {
1546+
// The shared_ptr is always given to C++ code, so construct a new shared_ptr
1547+
// that is given a custom deleter. The custom deleter increments the python
1548+
// reference count to bind the python instance lifetime with the lifetime
1549+
// of the shared_ptr.
1550+
//
1551+
// This enables things like passing the last python reference of a subclass to a
1552+
// C++ function without the python reference dying.
1553+
//
1554+
// Reference cycles will cause a leak, but this is a limitation of shared_ptr
1555+
return std::shared_ptr<T>((T*)v_h.value_ptr(),
1556+
shared_ptr_deleter{handle((PyObject*)v_h.inst).inc_ref()});
1557+
}
1558+
};
1559+
15271560
/// Type caster for holder types like std::shared_ptr, etc.
15281561
/// The SFINAE hook is provided to help work around the current lack of support
15291562
/// for smart-pointer interoperability. Please consider it an implementation
@@ -1566,7 +1599,7 @@ struct copyable_holder_caster : public type_caster_base<type> {
15661599
bool load_value(value_and_holder &&v_h) {
15671600
if (v_h.holder_constructed()) {
15681601
value = v_h.value_ptr();
1569-
holder = v_h.template holder<holder_type>();
1602+
holder = holder_retriever<holder_type>::get_derivative_holder(v_h);
15701603
return true;
15711604
} else {
15721605
throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "

tests/test_smart_ptr.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -397,4 +397,36 @@ TEST_SUBMODULE(smart_ptr, m) {
397397
list.append(py::cast(e));
398398
return list;
399399
});
400+
401+
// For testing whether a python subclass of a C++ object dies when the
402+
// last python reference is lost
403+
struct SpBase {
404+
// returns true if the base virtual function is called
405+
virtual bool is_base_used() { return true; }
406+
407+
SpBase() = default;
408+
SpBase(const SpBase&) = delete;
409+
virtual ~SpBase() = default;
410+
};
411+
412+
struct PySpBase : SpBase {
413+
bool is_base_used() override { PYBIND11_OVERRIDE(bool, SpBase, is_base_used); }
414+
};
415+
416+
struct SpBaseTester {
417+
std::shared_ptr<SpBase> get_object() { return m_obj; }
418+
void set_object(std::shared_ptr<SpBase> obj) { m_obj = obj; }
419+
bool is_base_used() { return m_obj->is_base_used(); }
420+
std::shared_ptr<SpBase> m_obj;
421+
};
422+
423+
py::class_<SpBase, std::shared_ptr<SpBase>, PySpBase>(m, "SpBase")
424+
.def(py::init<>())
425+
.def("is_base_used", &SpBase::is_base_used);
426+
427+
py::class_<SpBaseTester>(m, "SpBaseTester")
428+
.def(py::init<>())
429+
.def("get_object", &SpBaseTester::get_object)
430+
.def("set_object", &SpBaseTester::set_object)
431+
.def("is_base_used", &SpBaseTester::is_base_used);
400432
}

tests/test_smart_ptr.py

+44
Original file line numberDiff line numberDiff line change
@@ -316,3 +316,47 @@ def test_shared_ptr_gc():
316316
pytest.gc_collect()
317317
for i, v in enumerate(el.get()):
318318
assert i == v.value()
319+
320+
321+
def test_shared_ptr_cpp_arg():
322+
import weakref
323+
324+
class PyChild(m.SpBase):
325+
def is_base_used(self):
326+
return False
327+
328+
tester = m.SpBaseTester()
329+
330+
obj = PyChild()
331+
objref = weakref.ref(obj)
332+
333+
tester.set_object(obj)
334+
del obj
335+
pytest.gc_collect()
336+
337+
# python reference is still around since C++ has it now
338+
assert objref() is not None
339+
assert tester.is_base_used() is False
340+
assert tester.get_object() is objref()
341+
342+
343+
def test_shared_ptr_arg_identity():
344+
import weakref
345+
346+
tester = m.SpBaseTester()
347+
348+
obj = m.SpBase()
349+
objref = weakref.ref(obj)
350+
351+
tester.set_object(obj)
352+
del obj
353+
pytest.gc_collect()
354+
355+
# python reference is still around since C++ has it
356+
assert objref() is not None
357+
assert tester.get_object() is objref()
358+
359+
# python reference disappears once the C++ object releases it
360+
tester.set_object(None)
361+
pytest.gc_collect()
362+
assert objref() is None

0 commit comments

Comments
 (0)