What is the nanobind equivalent of the Boost.Python function manage_new_object?

125 views Asked by At

I'm trying to wrap a function that exposes a raw, heap-allocated pointer, and I want Python to be responsible for its lifetime. This is usually achieved in Boost.Python with using the return_value_policy of manage_new_object when wrapping it, is there a similar way to achieve this in nanobind?

1

There are 1 answers

0
got here On BEST ANSWER

In nanobind, the equivalent to return_value_policy::manage_new_object is rv_policy::take_ownership.

This is the documentation of manage_new_object:

manage_new_object is a model of ResultConverterGenerator which can be used to wrap C++ functions which return a pointer to an object allocated with a new-expression, and expect the caller to take responsibility for deleting that object

And this is the documentation for take_ownership:

Create a thin Python object wrapper around the returned C++ instance without making a copy and transfer ownership to Python. When the Python wrapper is eventually garbage collected, nanobind will call the C++ delete operator to free the C++ instance. [...]use[s] this policy to transfer ownership of a heap-allocated C++ instance to Python[...]

Which shows they are functionally equivalent. It is important to note, that this is the default rv_policy in nanobind for raw pointers, so you can disregard explicitly defining it:

m.def("my_func", &my_func, /*rv_policy::take_ownership*/);