如何通过 ctypes 将 Python 列表的(非空)列表传递给 C++?

How to pass (non-empty) list of lists from Python to C++ via ctypes?

我有一些格式的数据:

data = [[1,1,1],[2,2,2],[3,3,3]]

如何通过 ctypes 将其传递给 C++?

我可以像这样单独传递每个列表:

import ctypes

temp1 = [1,1,1]
temp2 = [2,2,2]
temp3 = [3,3,3]

list1 = (ctypes.c_int * 3)(*temp1)     #NO IDEA WHAT THE * MEANS
list2 = (ctypes.c_int * 3)(*temp2)
list3 = (ctypes.c_int * 3)(*temp3)

但在那之后,如果我尝试将所有这些列表附加到 'data'...

data.append(list1)
data.append(list2)
data.append(list3)

data_final = (ctypes.?????? * 3)(*data)

我应该在 ??????谢谢

?????? 应该是 ctypes.c_int * 3 * 3

data_final = (ctypes.c_int * 3 * 3)(*data)
[list(a) for a in data_final]
# --> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

郑重声明,不要这样做

data = []
data.append(list1)
data.append(list2)
data.append(list3)

这是python,不是c++,做

data = [list1, list2, list3]

见鬼,因为你只是要把它传递给一个函数 do

data_final = (ctypes.c_int * 3 * 3)(list1, list2, list3)

并完全跳过 data 步骤


只是为了最 pythonic 的方式,如果我在 N x M 列表列表 py_list 中有数据,我会做

c_array = (c_types.c_int * M * N)(*[(c_types.c_int * M)(*lst) for lst in py_list])