Use SWIG to port C ++ <vector> as a python NumPy array

I have a C ++ library that defines the following (and more similar to them) types:

typedef std::vector< double > DoubleVec; typedef std::vector< DoubleVec > DoubleVecVec; typedef std::vector< int > IntVec; typedef std::vector< IntVec > IntVecVec; 

I am trying to create a python interface for a library that processes such objects. As the title says, I would like my interface to be converted to / from C ++ std::vector and numpy ndarray .

I saw both numpy.i provided by numpy people and std_vector.i from SWIG people. The problems are that numpy.i was created to handle C / C ++ arrays (not C ++ vectors), and std_vector.i does not convert directly to / from numpy arrays.

Any ideas?

I saw that the FEniCS project did something similar, but their project is so large that it’s hard for me to find how they will accomplish this specific task.

+7
source share
1 answer

Try this as a starting point.

 %include "numpy.i" %apply (size_t DIM1, double* IN_ARRAY1) {(size_t len_, double* vec_)} %rename (foo) my_foo; %inline %{ int my_foo(size_t len_, double* vec_) { std::vector<double> v; v.insert(v.end(), vec_, vec_ + len_); return foo(v); } %} %apply (size_t DIM1, size_t DIM2, double* IN_ARRAY2) {(size_t len1_, size_t len2_, double* vec_)} %rename (bar) my_bar; %inline %{ int my_bar(size_t len1_, size_t len2_, double* vec_) { std::vector< std::vector<double> > v (len1_); for (size_t i = 0; i < len1_; ++i) { v[i].insert(v[i].end(), vec_ + i*len2_, vec_ + (i+1)*len2_); } return bar(v); } %} 
+2
source

All Articles