[QUESTION] How to pass std::unique_ptr ownership to class member? · Issue #2583 · pybind/pybind11 (original) (raw)

Given a C++ library that passes std::unique_ptr ownership to a class member, how could it be wrapped with pybind11?

Minimal example, distilled from production code: unique_ptr_member.h

PyCLIF supports this pattern: bindings, tests.

We are working on integrating pybind11 into PyCLIF and need to find some way to keep supporting the existing wrappers, like the minimal example, or provide an alternative/workaround. What are our options?

Some background:

Quoting from the relevant pybind11 documentation:

void do_something_with_example(std::unique_ptr<Example> ex) { ... }

The above signature would imply that Python needs to give up ownership of an object that is passed to this function, which is generally not possible (for instance, the object might be referenced elsewhere).

The PyCLIF approach to giving up ownership is implemented here.

Quoting from the source code comment there:

// Will give up ownership of the pointee if the pointee is a) owned by this
// Instance, and b) if this Instance is the only pointer to the pointee.

Questions about the "Missing value for wrapped C++ type" error message are very rare. While having its dangers, on balance this feature appears to be very useful.