How to convert numpy arrays to vector<int>& (reference) with SWIG How to convert numpy arrays to vector<int>& (reference) with SWIG numpy numpy

How to convert numpy arrays to vector<int>& (reference) with SWIG


I agree with @pschill: it’s not possible to get an std::vector without copying data.

One alternative is to use the std::span class template (introduced in C++20), or a similar span class template defined in a library.

Creating a std::span<int> would provide a view of existing data in a numpy array, and provide many convenient member functions (such as operator[], iterators, front(), back(), etc.) in C++.

Creating a span would never copy data from the numpy array.


You can refer to the Facebook faiss library, which achieves what you want to achieve, in a more elegant way By:

Python-specific: numpy array <-> C++ pointer interface (vector)

You can see the code on its Github page.