如何使用ctypes在Python中模拟动态大小的C结构

2024-10-01 11:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一些python代码来与广泛使用结构的C DLL进行交互。在

其中一个结构包含嵌套结构。我知道这不是ctypes模块的问题。问题是,在C语言中,有一个常用的结构是通过宏定义的,因为它包含一个“静态”长度数组,它可以变化。这很令人困惑,所以这里有一些代码

struct VarHdr {
    int size;
}

#define VAR(size) \
    struct Var {
        VarHdr hdr;
        unsigned char Array[(size)];
    }

然后在其他类似的结构中使用

^{pr2}$

接下来的问题是如何在Python中模拟这个过程,从而在pythong脚本和DLL之间来回传递生成的结构。在

顺便说一句,我知道我可以硬编码其中的数字,但有几个实例,这个“VAR”的大小各不相同。在


Tags: 模块代码size定义var静态数组ctypes
1条回答
网友
1楼 · 发布于 2024-10-01 11:28:17

一旦知道尺寸,就用工厂来定义结构。在

http://docs.python.org/library/ctypes.html#variable-sized-data-types

Another way to use variable-sized data types with ctypes is to use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis.

(未测试)示例:

def define_var_hdr(size):
   class Var(Structure):
       fields = [("size", c_int),
                 ("Array", c_ubyte * size)]

   return Var

var_class_10 = define_var_hdr(10)
var_class_20 = define_var_hdr(20)
var_instance_10 = var_class_10()
var_instance_20 = var_class_20()

相关问题 更多 >