Im trying to convert a Python list of lists of floats into a C double ** ptr
lst = [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
c_dbl_ptr = (ctypes.c_double * len(lst) * len(lst[0])) (*(tuple(tuple(sublist) for sublist in lst)))
Which yields IndexError: invalid index
This method is from How do I convert a Python list of lists of lists into a C array by using ctypes? but it seems im doing something wrong when trying to apply it to a 2d list.
A
double**is an pointer to one or moredouble*, so each row of doubles needs to be in a double array, and each of those separate arrays used as initializers to adouble*array:Output:
Maybe easier to read in steps, but not quite equivalent since it assumes all the sub-lists are the same length. The former code supports variable length sub-lists.
If instead you really just need a 2D array, the original code had the array sizes reversed. In
ctypes, a Cdouble[3][4]is declared with the sizes in reverse, e.g.,ctypes.c_double * 4 * 3.4 * ctypes.c_double * 3or3 * (4 * ctypes.c_double)also work. Basically, the row multiplication has to happen first.Output: