Convert a 2D numpy array to C++ short**? Convert a 2D numpy array to C++ short**? numpy numpy

Convert a 2D numpy array to C++ short**?


You can use ctypes's c_short and POINTER to help with the intermediate conversion. The following function turns a numpy array into a C-type 2darray that can be passed into a C function expecting a short **.

def c_short_2darr(numpy_arr):  c_short_p = POINTER(c_short)  arr = (c_short_p * len(numpy_arr) ) ()  for i in range(len(numpy_arr)):    arr[i] = (c_short * len(numpy_arr[i]))()    for j in range(len(numpy_arr[i])):      arr[i][j] = numpy_arr[i][j]  return arr

Note, I modified func_py and CPPClass::func to take 2 extra parameters, width and length of the given array. With this, CPPClass::func can print out all of elements of the array:

// ...void CPPClass::func(unsigned short **array, size_t w, size_t h){    for(size_t i = 0; i < w; ++i)    {      for(size_t j = 0; j < h; ++j)          cout << array[i][j] << ", ";      cout << '\n';    }}// ...void func_py(CPPClass *myClass,             unsigned short **array,              size_t w, size_t h){    myClass->func(array, w, h);}

With that helper function defined, the following should now work:

>>> arr = numpy.array([ [1,2,3], [4,5,6] ])>>> arrarray([[1, 2, 3],       [4, 5, 6]])>>> cpplib.func_py(cppobj, c_short_2darr(arr), 2, 3)1, 2, 3,4, 5, 6,0