Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pybind11 - Returning a pointer to a container of unique_ptr

Tags:

pybind11

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);
}
like image 209
AdrianH Avatar asked Oct 16 '22 09:10

AdrianH


1 Answers

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;
like image 182
AdrianH Avatar answered Oct 21 '22 08:10

AdrianH