您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python,ctypes,多维数组

Python,ctypes,多维数组

这是一个如何将多维数组与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

我使用的是Python 2,而您问题上的标记表明您使用的是python3。但是,我认为这不会有所作为。

python 2022/1/1 18:34:12 有205人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶