title: Make a C++ class look like a numpy array using swig
body: <p>What's a good way to expose a C++ class that provides an array-like interface for use with numpy (scipy)?</p>
  
  <p>By array-like interface I mean something like:</p>
  
  <pre><code>//file:Arr.h
  class Arr{
  public:
      int n_rows;
      int n_cols;
      float* m_data;
  
      Arr(int r, int c, float v);
      virtual ~Arr();
      float get(int i, int j);
      void set(int i, int j, float v);
  
      long data_addr(){
          return (long)(m_data);
      }
  };
  </code></pre>
  
  <p>Constraints:</p>
  
  <ul>
  <li>I only care about classes that store their underlying data as contiguous flat arrays,</li>
  <li>The class will provide public access to the raw storage (probably through a function),</li>
  <li>I cannot add python specific code to the C++ header/source files (we do not want 
  to have a Python dependency for the C++ code) thus any modifications on the C++
  side have to be done via SWIG (e.g. <code>%extend</code>).</li>
  </ul>
  
  <p>My current approach is to put a <code>pythoncode</code> block in my SWIG <code>.i</code> file
  that looks something like</p>
  
  <pre><code>%pythoncode{
  def arraylike_getitem(self, arg1,arg2 ):
     # the actual implementation to handle slices
     # is pretty complicated but involves:
     # 1. constructing an uninitialized  numpy array for return value
     # 2. iterating over the indices indicated by the slices,
     # 3. calling self.getValue for each of the index pairs,
     # 4. returning the array
  
  # add the function to the ArrayLike class
  Arr.__getitem__=arraylike_getitem
  %}
  </code></pre>
  
  <p>where <code>ArrayLike</code> is the C++ class that holds the numerical data (as a flat array),
  and provides member functions to get/set individual values.</p>
  
  <p>The main drawback is step 1. above: I have to make a copy of any slice
  that I take of my c-array class.  (The main advantage is that by returning a
  numpy array object, I know that I can use it in any numpy operations that I want.)</p>
  
  <p>I can imagine two approaches for improving this:</p>
  
  <ol>
  <li>Adding (via SWIG <code>%extend</code>) additional functionality to the c class, and or</li>
  <li>having the python function return an array-slice proxy object,</li>
  </ol>
  
  <p>My main hang-up is not knowing what interface an object needs to (efficiently) implement in order to quack like a numpy array.</p>
  
  <p><strong>Test Case</strong></p>
  
  <p>Here's my test setup:</p>
  
  <pre><code>//file:Arr.h
  class Arr{
  public:
      int n_rows;
      int n_cols;
      float* m_data;
  
      Arr(int r, int c, float v);
      virtual ~Arr();
      float get(int i, int j);
      void set(int i, int j, float v);
  
      long data_addr(){
          return (long)(m_data);
      }
  };
  
  //-----------------------------------------------------------
  
  //file Arr.cpp
  #include "Arr.h"
  
  Arr::Arr(int r, int c, float v): n_rows(r), n_cols(c), m_data(0){
      m_data=new float[ r*c ];
      for( int i=0; i&lt;r*c; ++i){
          m_data[i]=v;
      }
  }  
  Arr::~Arr(){
      delete[] m_data;
  }
  
  float Arr::get(int i, int j){
      return m_data[ i*n_cols+j];
  }
  void Arr::set(int i, int j, float v){
      m_data[i*n_cols+j]=v;
  }
  
  //--------------------------------------------------------------------
  //file:arr.i
  %module arr
  
  %{
  #include "Arr.h"
  #include &lt;/usr/lib64/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h&gt;
  #include &lt;python2.7/Python.h&gt;
  %}
  
  %include "Arr.h"
  
  
  %pythoncode{
  
  # Partial solution (developed in constructing the question): allows operations between 
  # arr objects and numpy arrays (e.g. numpy_array+arr_object is OK)
  # but does not allow slicing (e.g. numpy_array[::2,::2]+arr_objec[::2,::2])
  # TODO: figure out how to get slices without copy memory
  def arr_interface_map(self):
      res={ 'shape':(self.n_rows, self.n_cols), 'typestr':'&lt;f4', 'data': self.data_addr(),0), 'version':3 }
      return res
  
  Arr.__array_interface__=property( arr_interface_map )
  
  
  }
  
  //---------------------------------------------------------
  #file: Makefile
  INCLUDE_FLAGS = -I/usr/include/python2.7 
  
  arr_wrap.cpp: arr.i Arr.h
       swig -c++ -python -o $@ ${INCLUDE_FLAGS} arr.i
  
  _arr.so: arr_wrap.o Arr.o
      g++ -shared -o _arr.so arr_wrap.o Arr.o 
  
  clean:
      rm -f *.o *_wrap.cpp *.so
  
  all: _arr.so
  </code></pre>
  
  <p>If I can get this <code>Arr</code> class to work with <code>numpy</code>, then I've succeeded.</p>
  
  <p><strong>Edit:</strong> 
  From <a href="https://stackoverflow.com/questions/5424324/fast-conversion-of-c-c-vector-to-numpy-array?rq=1">this related question</a> it looks like <code>__array_interface__</code> will be part of the solution (TBD: how to use it?)</p>