Create 2D c_types array in Python and use it in a C function

Viewed 80

I searched on Google and I can't find a solution. I just want to create a 2D pointer array that make a reference of an existing python array in order to send it in a C Function thanks to c_types.

tab is a existing 1D array, and it worked:

arr = (c_int * 1000000)(*tab)
Basic.Basic_c.quicksort.restype = POINTER(c_int )
c = Basic.Basic_c.quicksort(arr)

With 2D array:

Matrix = [[0 for x in range(8)] for y in range(5)];
arr = ((c_int * 8)*5)(*Matrix)

That didn't work, create a error:

TypeError: expected c_long_Array_8 instance, got list

I can't find a solution.

1 Answers

Instead of using 2d list, you can use a tuple of tuples. So, after you created your matrix, convert it to a tuple as below.

Matrix = [[0 for x in range(8)] for y in range(5)];
Matrix = tuple(map(tuple, Matrix))
arr = ((c_int * 8)*5)(*Matrix)
Related