pybind11 array from 2d vector without copy

Viewed 689

How can I create a 2d numpy array from a vector of vectors in pybind11?

I'm looking for a way to do this fast & without copy (so move?), and I'd like to do it in a templated fashion.

So far I have:

template< typename T >
py::array
array2d_from_vector(std::vector<std::vector<T>> & m) {
    if (m.empty()) return py::array_t<T>();
    std::vector<std::vector<T>>* ptr = new std::vector<std::vector<T>>(std::move(m));
    auto capsule = py::capsule(ptr, [](void* p) {
            delete reinterpret_cast<std::vector<std::vector<T>>*>(p);
    });
    return py::array_t<T>(
            {ptr->size(), ptr->at(0).size()},           // shape of array
            {ptr->at(0).size()*sizeof(T), sizeof(T)},   // c-style contiguous strides
            capsule);
}

which returns a nonsense 2d array to python with values like:

[[ 4.0852747e+30  3.0677226e-41  4.0853762e+30  3.0677226e-41]...

So what am I missing! I'm guessing it has to do with the way vectors hold their data, but my values should be between 0 and 1.

0 Answers
Related