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>Using NumPy and <code>numpy.i</code>, this is quite easy</p>

<p>Interface header</p>

<pre><code>#pragma once
void fun(int** outArray, int* nRows, int* nCols);
</code></pre>

<p>Implementation</p>

<pre><code>#include "test.h"
#include &lt;malloc.h&gt;
void fun(int** outArray, int* nRows, int* nCols) {
  int _nRows = 100;
  int _nCols = 150;
  int* _outArray = (int*)malloc(sizeof(int)*_nRows*_nCols);
  *outArray = _outArray;
  *nRows = _nRows;
  *nCols = _nCols;
}
</code></pre>

<p>SWIG interface header</p>

<pre><code>%module example
%{
  #define SWIG_FILE_WITH_INIT
  #include "test.h"
%}

%include "numpy.i"

%init
%{
  import_array();
%}

%apply (int** ARGOUTVIEWM_ARRAY2, int* DIM1, int* DIM2) {(int** outArray, int* nRows, int* nCols)}
%include "test.h"
</code></pre>

<p>The typemap <code>ARGOUTVIEWM_ARRAY2</code> creates a managed NumPy array and free is automatically called, when the NumPy object is destroyed in Python.</p>

<p>If you want to create the wrapper yourself using the Python C API, you can look into the generated code made by SWIG using <code>numpy.i</code></p>

python c++ arrays numpy swig