8

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.

1 Answer 1

4

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);
}
%}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.