Recently I’m doing a project which a function is heavily called, so I want to using C code in this part. I’m a newbie to ctypes, please forgive me if my question is very easy.
Here I have a 2d list in python:
L = [[1],[1,2],[1,2,3]]
I want call a function in C module with it as parameter. Since there is no 2d-list in C I want to convert it to an array of *int.
I don’t want an normal 2D C array because each length of entry is different.
What I’ve done in python part is:
L = [[1],[1,2],[1,2,3]]
entrylist = []
for entry in L:
c_entry = (ctypes.c_int * len(entry))(*entry) # c_entry is the C array version of entry
entrylist.append(c_entry)
c_L = (ctypes.POINTER(ctypes.c_int) * len(entrylist))(*entrylist) # create an array of integer pointer, then initial it
c_L is an “LP_c_long_Array_14 object”, when len(L) == 14.
also, I can print it out perfectly by using
for i in range(len(L)):
for j in range(len(L[i])):
print(L[i][j], end = ' ')
print()
On the other hand, in C code, I define my function as:
int fun(int** c_L)
int fun( (int * c_L)[])
neither works. ctypes throws a “Don’t know how to convert parameter 1” Error.
So, please tell me how to make it work? Thank you very much.
You are almost there, you just need some tweaks.
where the C side of things looks like:
If this doesn’t work, then it may be of use to explicitly cast all your arguments to the c library function.