title: Handling C++ arrays in Cython (with numpy and pytorch)
body: <p>I am trying to use <code>cython</code> to wrap a C++ library (<code>fastText</code>, if its relevant). The C++ library classes load a very large array from disk. My wrapper instantiates a class from the C++ library to load the array, then uses <code>cython</code> memory views and <code>numpy.asarray</code> to turn the array into a <code>numpy</code> array, then calls <code>torch.from_numpy</code> to create a tensor. </p>
  
  <p>The problem arising is how to handle deallocating the memory for the array. </p>
  
  <p>Right now, I get <code>pointer being freed was not allocated</code> when the program exits. This is, I expect, because both the C++ code and <code>numpy</code>/<code>pytorch</code> are trying to manage the same chunk of RAM. </p>
  
  <p>I could simply comment out the destructor in the C++ library, but that feels like its going to cause me a different problem down the road.</p>
  
  <p>How should I approach the issue?  Is there any kind of best practices documentation somewhere on how to handle memory sharing with C++ and <code>cython</code>?  </p>
  
  <p>If I modify the C++ library to wrap the array in a <code>shared_ptr</code>, will <code>cython</code> (and <code>numpy</code>, <code>pytorch</code>, etc.) share the <code>shared_ptr</code> properly?  </p>
  
  <p>I apologize if the question is naive; Python garbage collection is very mysterious to me.</p>
  
  <p>Any advice is appreciated. </p>