如何使用ctypes在Python中模拟动态大小的C结构 [英] How do I emulate a dynamically sized C structure in Python using ctypes

查看:82
本文介绍了如何使用ctypes在Python中模拟动态大小的C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing some python code to interact with a C DLL that uses structures extensively.

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

One of those structures contains nested structures. I know that this is not a problem for the ctypes module. The problem is that there is an often used structure that, in C, is defined via macro because it contains an "static" length array that can vary. That is confusing so here's some code

struct VarHdr {
    int size;
}

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

然后将其用于其他结构

struct MySruct {
    int foo;
    VAR(20) stuffArray;
}

然后问题就变成了我该如何在Python中以一种生成的结构可以在pythong脚本和DLL之间来回传递。

The question then becomes how can I emulate this in Python in a way that the resulting structure can be passed back and forth between my pythong script and the DLL.

顺便说一句,我知道我可以对其中的数字进行硬编码,但是整个 VAR的一些实例的大小不同。

BTW, I know that I can just hardcode the number in there but there are several instances of this "VAR" throughout that have different sizes.

推荐答案

一旦知道大小,只需使用工厂定义结构。

Just use a factory to define the structure once the size is known.

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


将可变大小数据
类型与ctypes结合使用的另一种方法是使用Python的
动态特性,并在
逐案的基础上,
(重新)定义所需的
大小后重新定义数据类型。

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()

这篇关于如何使用ctypes在Python中模拟动态大小的C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆