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

Python结构中的动态数组和结构

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

Python结构中的动态数组和结构

我正在对OP的需求做一些假设,如果有更简单的方法可以满足我的要求,那是我的想法:

演示

import stringfrom ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLLclass Row(Structure):    _fields_ = [('cols_count', c_int),      ('cols', POINTER(c_char_p))]    def __init__(self,cols):        self.cols_count = cols        # Allocate an array of character pointers        pc = (c_char_p * cols)()        self.cols = cast(pc,POINTER(c_char_p))class Unit(Structure):    _fields_ = [('rows_count', c_int),     ('rows',POINTER(Row))]    def __init__(self,rows,cols):        self.rows_count = rows        # Allocate an array of Row structures.        # This does NOT call __init__.        pr = (Row * rows)()        # Call init manually with the column size.        for r in pr: r.__init__(cols)        self.rows = cast(pr,POINTER(Row))unit = Unit(2,3)# Stuff some strings ('aaaaa','bbbbb',etc.)for i in xrange(unit.rows_count):    for j in xrange(unit.rows[i].cols_count):        unit.rows[i].cols[j] = string.ascii_lowercase[i*5+j]*5dll = CDLL('test.dll')dll.my_func(byref(unit))

测试

#include <stdio.h>struct _rows {    int cols_count;    char **cols;};struct _unit {    int rows_count;    struct _rows *rows;};__declspec(dllexport) int my_func(struct _unit *param){    int i,j;    for(i=0;i<param->rows_count;i++)        for(j=0;j<param->rows[i].cols_count;j++) printf("%d,%d = %sn",i,j,param->rows[i].cols[j]);    return 0;}

生成文件

与Visual Studio 2010一起编译。

test.dll: test.c    cl /W4 /LD test.c

输出量

0,0 = aaaaa0,1 = bbbbb0,2 = ccccc1,0 = fffff1,1 = ggggg1,2 = hhhhh


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

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

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