Hiperfly
Hiperfly

Reputation: 178

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

I have some data in the format:

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

How can I pass it to C++ via ctypes?

I can pass individually each one of the lists like this:

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)

But after that if I try to append all these lists into 'data'...

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

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

What type am I supposed to put in the ????? Thanks

Upvotes: 0

Views: 252

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12157

?????? should be 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]]

For the record, don't do

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

This is python, not c++, do

data = [list1, list2, list3]

Hell since you're just going to pass it to a function do

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

and skip the data step entirely


Just for the most pythonic way, if I had data in a N x M list of lists py_list, I'd do

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

Upvotes: 1

Related Questions