这是一个如何将多维数组与Python和ctypes一起使用的示例。
我编写了以下C代码,并gcc
在MinGW中用于将其编译为slib.dll
:
#include <stdio.h>
typedef struct TestStruct {
int a;
float array[30][4];
} TestStruct;
extern void print_struct(TestStruct *ts) {
int i,j;
for (j = 0; j < 30; ++j) {
for (i = 0; i < 4; ++i) {
printf("%g ", ts->array[j][i]);
}
printf("\n");
}
}
请注意,该结构包含一个“二维”数组。
然后,我编写了以下Python脚本:
from ctypes import *
class TestStruct(Structure):
_fields_ = [("a", c_int),
("array", (c_float * 4) * 30)]
slib = CDLL("slib.dll")
slib.print_struct.argtypes = [POINTER(TestStruct)]
slib.print_struct.restype = None
t = TestStruct()
for i in range(30):
for j in range(4):
t.array[i][j] = i + 0.1*j
slib.print_struct(byref(t))
当我运行Python脚本时,它调用了C函数,该函数打印出多维数组的内容:
C:\>slib.py
0.1 0.2 0.3 0.4
1.1 1.2 1.3 1.4
2.1 2.2 2.3 2.4
3.1 3.2 3.3 3.4
4.1 4.2 4.3 4.4
5.1 5.2 5.3 5.4
... rest of output omitted