Skip to content

Commit

Permalink
test_smart_ptr: Add test for reclaim_from_cpp logic
Browse files Browse the repository at this point in the history
  • Loading branch information
EricCousineau-TRI committed Apr 14, 2020
1 parent c1f7de5 commit ced13e9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
23 changes: 23 additions & 0 deletions tests/test_smart_ptr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -462,4 +462,27 @@ TEST_SUBMODULE(smart_ptr, m) {
[](std::shared_ptr<SharedPtrHeld> obj) {
return obj != nullptr && obj->value == 10;
});

// Test passing ownership of registered, but unowned, C++ instances back to
// Python. This happens when a raw pointer is passed first, and then
// ownership is transfered.
struct UniquePtrHeldContainer {
UniquePtrHeldContainer() {
value_ = std::make_unique<UniquePtrHeld>(10);
}
UniquePtrHeld* get() const {
return value_.get();
}
using Ptr = std::unique_ptr<UniquePtrHeld>;
Ptr reset(Ptr to) {
Ptr from = std::move(value_);
value_ = std::move(to);
return from;
}
std::unique_ptr<UniquePtrHeld> value_;
};
py::class_<UniquePtrHeldContainer>(m, "UniquePtrHeldContainer")
.def(py::init())
.def("get", &UniquePtrHeldContainer::get, py::return_value_policy::reference_internal)
.def("reset", &UniquePtrHeldContainer::reset);
}
14 changes: 14 additions & 0 deletions tests/test_smart_ptr.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,17 @@ def test_unique_ptr_overload_fail():
out = m.unique_ptr_overload(obj, m.SecondT())
assert out["obj"] is obj
assert out["overload"] == 2


def test_unique_ptr_held_container_from_cpp():

def check_reset(obj_new):
c = m.UniquePtrHeldContainer()
obj = c.get()
assert obj is not None
obj_ref = c.reset(obj_new)
assert obj is obj_ref
assert c.get() is obj_new

check_reset(obj_new=m.UniquePtrHeld(10))
check_reset(obj_new=None)

0 comments on commit ced13e9

Please sign in to comment.