栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python,ctypes,多维数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 = 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。但是,我认为这不会有所作为。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667967.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号