title: Passing and returning numpy arrays to C++ methods via Cython
body: <p>There are lots of questions about using numpy in cython on this site, a particularly useful one being <a href="https://stackoverflow.com/questions/3046305/simple-wrapping-of-c-code-with-cython">Simple wrapping of C code with cython</a>.</p>
  
  <p>However, the cython/numpy interface api <a href="http://docs.cython.org/src/userguide/memoryviews.html" rel="noreferrer">seems to have changed a bit</a>, in particular with ensuring the passing of memory-contiguous arrays.</p>
  
  <p>What is the best way to write a wrapper function in cython that:</p>
  
  <ul>
  <li>takes a numpy array that is likely but not necessarily contiguous</li>
  <li>calls a C++ class method with the signature <code>double* data_in, double* data_out</code></li>
  <li>returns a numpy array of the <code>double*</code> that the method wrote to?</li>
  </ul>
  
  <p>My try is below:</p>
  
  <pre><code>cimport numpy as np
  import numpy as np # as suggested by jorgeca
  
  cdef extern from "myclass.h":
      cdef cppclass MyClass:
          MyClass() except +
          void run(double* X, int N, int D, double* Y)
  
  def run(np.ndarray[np.double_t, ndim=2] X):
      cdef int N, D
      N = X.shape[0]
      D = X.shape[1]
  
      cdef np.ndarray[np.double_t, ndim=1, mode="c"] X_c
      X_c = np.ascontiguousarray(X, dtype=np.double)
  
      cdef np.ndarray[np.double_t, ndim=1, mode="c"] Y_c
      Y_c = np.ascontiguousarray(np.zeros((N*D,)), dtype=np.double)
  
      cdef MyClass myclass
      myclass = MyClass()
      myclass.run(&lt;double*&gt; X_c.data, N, D, &lt;double*&gt; Y_c.data)
  
      return Y_c.reshape(N, 2)
  </code></pre>
  
  <p>This code compiles but is not necessarily optimal. Do you have any suggestions on improving the snippet above?</p>
  
  <p><s>and (2) throws and "np is not defined on line <code>X_c = ...</code>") when calling it at runtime.
  The exact testing code and error message are the following: </p>
  
  <pre><code>import numpy as np
  import mywrapper
  mywrapper.run(np.array([[1,2],[3,4]], dtype=np.double))
  
  # NameError: name 'np' is not defined [at mywrapper.pyx":X_c = ...]
  # fixed!
  </code></pre>
  
  <p></s></p>