I've been using the excellent pybind11 library but have hit a brick wall. I need to return to Python a pointer to a non-copyable object (as the object contains unique_ptrs).
Generally this works fine with caveat of using return_value_policy::reference. However, returning a pointer to an object that has vector of non-copyable's results in a compilation error. It seems pybind wants to perform a copy in this case even though the return value policy is reference and the function explicitly returns a pointer.
Why is this and is there a workaround?
I am using VS2017 15.9.2 with the latest pybind11 off master
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <memory>
/* This fails to compile... */
struct myclass
{
std::vector<std::unique_ptr<int>> numbers;
};
/* ...but this works
struct myclass
{
std::unique_ptr<int> number;
};
*/
void test(py::module &m)
{
py::class_<myclass> pymy(m, "myclass");
pymy.def_static("make", []() {
myclass *m = new myclass;
return m;
}, py::return_value_policy::reference);
}
I worked this out
The copy constructor and assignment operator need to be explicitly deleted, i.e. adding the following allows pybind to recognise it cannot make a copy
myclass() = default;
myclass(const myclass &m) = delete;
myclass & operator= (const myclass &) = delete;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With