title: Using Smart Pointers in Cython for Dynamically Allocated Arrays
body: <p>I am writing a Python wrapper for a function call with the signature</p>
  
  <p><code>double** foo(double** arrayIn, int dim1, int dim2);</code></p>
  
  <p>and need to build <code>arrayIn</code> inside my Python wrapper. One possible solution for this is given <a href="https://www.reddit.com/r/C_Programming/comments/3dbwy9/cython_2d_memoryview_to_c_pointer_error/" rel="noreferrer">here.</a> However, since Cython includes support for smart pointers, I would prefer to implement that solution. One way to do this would be <a href="https://stackoverflow.com/questions/3477525/is-it-possible-to-use-a-c-smart-pointers-together-with-cs-malloc">a combination of malloc and a unique_ptr with a custom deleter.</a> Another (simpler) solution would be to use <a href="https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/memory.pxd" rel="noreferrer">the allocator class from libcpp.</a></p>
  
  <pre><code>import numpy as np
  cimport numpy as np
  from libcpp.memory cimport unique_ptr, allocator
  
  def testArray(int dim1, int dim2):
      cdef allocator[double *] ptr_al
      cdef unique_ptr[double *] myptr
      cdef np.ndarray arr
      cdef double[:,:] carr
  
      myptr.reset(ptr_al.allocate(dim1))
      arr = np.ndarray((dim1,dim2),dtype=np.float64,order='C')
      carr = arr
  
      myptr.get()[0] = &amp;carr[0,0]
      myptr.get()[1] = &amp;carr[1,0]
      myptr.get()[2] = &amp;carr[2,0]
  </code></pre>
  
  <p>This code compiles and executes correctly (with Cython 24.1, Python 3.5, VS2015). My concern is whether or not everything will be properly deallocated / garbage collected. My understanding is that Python is responsible for the <code>ndarray</code>, and <code>unique_ptr</code> should be responsible for the <code>double *[]</code> created by <code>allocator</code>. Is this correct, or will the code create a memory leak? Is there a way I could verify that everything has been properly deallocated?</p>