Skip to content Skip to sidebar Skip to footer

How Do I Convert A Python List Of Lists Of Lists Into A C Array By Using Ctypes?

As seen here How do I convert a Python list into a C array by using ctypes? this code will take a python array and transform it to a C array. import ctypes arr = (ctypes.c_int * le

Solution 1:

It works with tuples if you don't mind doing a bit of conversion first:

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))

Check that it's initialized correctly in row-major order:

>>>(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]

Or you can create an empty array and initialize it using a loop. enumerate over the rows and columns of the list and assign the data to a slice:

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

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

Solution 2:

I made the change accordingly

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]

The arr_instance is what you want.

Post a Comment for "How Do I Convert A Python List Of Lists Of Lists Into A C Array By Using Ctypes?"