这是一个如何将多维数组与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 = Nonet = TestStruct()for i in range(30): for j in range(4): t.array[i][j] = i + 0.1*jslib.print_struct(byref(t))当我运行Python脚本时,它调用了C函数,该函数打印出多维数组的内容:
C:>slib.py0.1 0.2 0.3 0.41.1 1.2 1.3 1.42.1 2.2 2.3 2.43.1 3.2 3.3 3.44.1 4.2 4.3 4.45.1 5.2 5.3 5.4... rest of output omitted
我使用的是Python 2,而您问题上的标记表明您使用的是Python3。但是,我认为这不会有所作为。



