1

I created my own 2D array class in C++ and got it to work with Python using SWIG. I also extended it to have some basic functionality like NumPy arrays. For example, I created a method in my Array2D class, getitem, which returns the elements of the array:

%extend Array2D{
    double __getitem__(vector<int> v) {
        return (*self)[v[0]][v[1]];
    }
}

After compiling the C++ extension using SWIG, I can import this into Python and get an Array2D object:

>>> import myclass
>>> A = myclass.Array2D(2,2,1.0)

which creates a 2x2 matrix of ones. Because of my extension method, I can retrieve individual elements just like with NumPy.

>>> A[0,1]
>>> 1.0

This is great and all, but when I try to use NumPy's mean function, I get the following error:

>>> mean(A)
>>> TypeError: in method 'dblArray2D___getitem__', argument 2 of type 'std::vector< int >'

It seems that NumPy's mean function doesn't know what to do with std::vector. What do I need to do with my getitem method or SWIG interface file to get my Array2D to use NumPy's mean function?

2
  • First of all I would suggest to pass v by reference, or even constant reference Commented Apr 20, 2014 at 22:52
  • related: stackoverflow.com/questions/18211783/… Commented May 4, 2015 at 17:26

1 Answer 1

1

My guess is that you have to provide an overload of the C++ __getitem__ in your %extend that accepts one int, because mean flattens the array so it probably calls array[i] i.e. with one index, not two.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you're right. I had to get array[i] to return the row vector. Then it all worked!

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.