title: How to declare 2D c-arrays dynamically in Cython
body: <p>I need to perform a lot of work using 2D numpy arrays of various sizes and I would like to offload these calculations onto cython. The idea is that my 2D numpy arrays would be passed from python to cython where it would be converted into c-array or memory view and used in a cascade of other c-level functions to do the calculations.</p>
  <p>After some profiling I ruled out using numpy arrays in cython due to some serious python overhead. Using memory views was MUCH faster and quite easy to use, but I suspect I can squeeze even more speedup from using c-arrays.</p>
  <p>Here is my question though - how can I declare a 2D c-array in cython without predefining its dimensions with set values? For example, I can create a c-array from numpy this way:</p>
  <pre><code>narr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]], dtype=np.dtype(&quot;i&quot;))
  
  cdef int c_arr[3][4]:
  for i in range(3):
      for j in range(4):
          c_arr[i][j] = narr[i][j]
  </code></pre>
  <p>and then pass it to a function:</p>
  <pre><code>cdef void somefunction(int c_Arr[3][4]):
      ...
  </code></pre>
  <p>But this implies I have a fixed sizde of array, which in my case will be useless. So I tried something like this:</p>
  <pre><code>narr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]], dtype=np.dtype(&quot;i&quot;))
  
  cdef int a = np.shape(narr)[0]
  cdef int b = np.shape(narr)[1]
  
  cdef int c_arr[a][b]:               # INCORRECT - EXAMPLE ONLY
  
  for i in range(a):
      for j in range(b):
          c_arr[i][j] = narr[i][j]
  </code></pre>
  <p>with the intention to pass it to a function like this:</p>
  <pre><code>cdef void somefunction(int a, int b, int c_Arr[a][b]):
      ...
  </code></pre>
  <p>But it doesn't work and the compilation fails with the error &quot;Not allowed in a constant expression&quot;. I suspect I need t do it with malloc/free somehow? I had a look at this problem (<a href="https://stackoverflow.com/questions/14119254/how-to-declare-2d-list-in-cython">How to declare 2D list in Cython</a>), but it does not provide the answer to my problem.</p>
  <h2>UPDATE:</h2>
  <p>It turns out that memory-views can be as fast as c-arrays if one makes sure that indexError checking in cython is switched-off for the memory views, which can be done by using cython compiler directive:</p>
  <pre><code># cython: boundscheck=False
  </code></pre>
  <p>Thanks @Veedrac for the tip!</p>