如何使用ctypes将列表列表的Python列表转换为C数组? [英] How do I convert a Python list of lists of lists into a C array by using ctypes?

查看:24
本文介绍了如何使用ctypes将列表列表的Python列表转换为C数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此处所示如何使用ctypes将Python列表转换为C数组?此代码将采用python数组并将其转换为C数组.

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 * len(pyarr))(*pyarr)

对列表列表或列表列表采取哪种处理方式?

Which would the way of doing the same with a list of lists or a lists of lists of lists?

例如,对于以下变量

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

谢谢!

为澄清起见,我试图获取一个包含整个多维数组而不是对象列表的对象.该对象的引用将是C DLL的输入,该C DLL需要3D数组.

Just to clarify, I am trying to get one object that contains the whole multidimensional array, not a list of objects. This object's reference will be an input to a C DLL that expects a 3D array.

推荐答案

使用元组,如果您不介意先进行一些转换:

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

这篇关于如何使用ctypes将列表列表的Python列表转换为C数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆