Convert a ctypes int** to numpy 2 dimensional array
<p>I have a c++ implementation wrapped with SWIG and compiled to a module which can be used by python.</p>

<p>I am using ctypes to call the function with ctype arguments, int double etc.
The output of my_function(ctype args) is an int**, i.e. it's a multidimensional array.</p>

<p>How can I cast this  into a 2D numpy array inside the python script? I have been looking at ctypes pointers but so far I have had no luck. I have spent many, many hours reading the C-API of python and numpy for use with SWIG, and implementing on the c++ side to return a numpy array has so far been incredibly hard and completely unsuccessful.</p>

<p>I don't think this can be done on the Python side; it will have to be done within the C/C++ layer using NumPy's C-API interface (<code>PyArray_SimpleNewFromData</code> is the relevant function â see <a href="http://stackoverflow.com/questions/30357115/pyarray-simplenewfromdata-example">this answer</a> for some details). <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/dist_metrics.pyx#L37" rel="nofollow">Here</a> is an example of this in a Cython script.</p>

<p>Note that handling of deallocation is complicated in this case: as far as I know, there's no mechanism to allow numpy to handle it automatically. You'll just have to make sure that whatever script deallocates the array doesn't do so when the numpy wrapper is still being used.</p>

<p>Edit: if your <code>int**</code> does not point to a contiguous memory block, I don't believe this will work. NumPy can only (easily) handle contiguous data buffers.</p>

python c++ arrays numpy swig