How to convert a list of Python list lists to a C array using ctypes?

As shown here How to convert a Python list to a C array using ctypes? this code will take a python array and convert it to a C array.

import ctypes
arr = (ctypes.c_int * len(pyarr))(*pyarr)

What is the way to do the same with list of lists or list of lists?

For example, for the following variable

list3d = [[[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]]]

I tried the following with no luck:

([[ctypes.c_double * 4] *2]*3)(*list3d)
# *** TypeError: 'list' object is not callable

(ctypes.c_double * 4 *2 *3)(*list3d)
# *** TypeError: expected c_double_Array_4_Array_2 instance, got list

Thanks!

EDIT: just to clarify, I'm trying to get a single object that contains the entire multidimensional array, not a list of objects. This object reference will be the entry into the C DLL, which expects a 3D array.

+4
source share
2 answers

, :

from ctypes import *

list3d = [
    [[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0]], 
    [[0.2, 1.2, 2.2, 3.2], [4.2, 5.2, 6.2, 7.2]],
    [[0.4, 1.4, 2.4, 3.4], [4.4, 5.4, 6.4, 7.4]],
]

arr = (c_double * 4 * 2 * 3)(*(tuple(tuple(j) for j in i) for i in list3d))

, :

>>> (c_double * 24).from_buffer(arr)[:]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 
 0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 
 0.4, 1.4, 2.4, 3.4, 4.4, 5.4, 6.4, 7.4]

. enumerate list :

arr = (c_double * 4 * 2 * 3)()

for i, row in enumerate(list3d):
    for j, col in enumerate(row):
        arr[i][j][:] = col
+2

a = [[[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]]]
arr = (((ctypes.c_float * len(a[0][0])) * len(a[0])) * len(a))
arr_instance=arr()
for i in range(0,len(a)):
  for j in range(0,len(a[0])):
    for k in range(0,len(a[0][0])):
      arr_instance[i][j][k]=a[i][j][k]

arr_instance - , .

0

All Articles