gpt4 book ai didi

python - python结构中的动态数组和结构

转载 作者:太空狗 更新时间:2023-10-30 00:37:08 25 4
gpt4 key购买 nike

我正在尝试使用 ctypes 在 python 中实现这个 C 结构:

struct _rows {
int cols_count;
char *cols[];
}

struct _unit {
int rows_count;
struct _rows *rows;
}

int my_func(struct _unit *param);

问题是 _rows.cols 是一个动态大小的 char 指针数组,而 _unit.rows 是一个动态大小的 _rows 结构数组。我如何在 python 中使用 ctypes 实现它?

我能够定义一个函数,它将返回一个具有可变数量的 char 指针的 _rows 结构:

def get_row(cols):
class Row(ctypes.Structure):
_fields_ = [("cols_count", ctypes.c_int),
("cols", ctypes.c_char_p * cols)
]

我不知道下一步该怎么做,一切都有些模糊,ctypes 文档也没有帮助。

最佳答案

我正在对 OP 的需求做出一些假设,如果有更简单的方法,我会喜欢建议,但这是我想出的:

演示.py

import string
from ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLL

class 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]*5

dll = CDLL('test.dll')
dll.my_func(byref(unit))

测试.c

#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 = %s\n",i,j,param->rows[i].cols[j]);
return 0;
}

生成文件

使用 Visual Studio 2010 编译。

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

输出

0,0 = aaaaa
0,1 = bbbbb
0,2 = ccccc
1,0 = fffff
1,1 = ggggg
1,2 = hhhhh

关于python - python结构中的动态数组和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com