spencerlyon2
spencerlyon2

Reputation: 9686

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

I have a C++ library that defines the following (and more like 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 to a library that handles objects like that. As the title states, I would like my interface to convert to/from C++ std::vector and numpy ndarray.

I have seen both numpy.i provided by the numpy people and std_vector.i from the SWIG people. The problems are that numpy.i was created to handle C/C++ arrays (not C++ vectors) and std_vector.i doesn't do conversion directly to/from numpy arrays.

Any ideas?

I have seen that the FEniCS project has done something like this, but their project is so large that I am having a hard time finding out just how they do this specific task.

Upvotes: 8

Views: 3237

Answers (1)

Oktalist
Oktalist

Reputation: 14734

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);
}
%}

Upvotes: 4

Related Questions