How to emulate dynamic size C structure in Python using ctypes

I am writing python code to interact with a C DLL that makes extensive use of structures.

One of these structures contains nested structures. I know this is not a problem for the ctypes module. The problem is that there is a commonly used structure, which in C is defined by a macro, because it contains an array of static length that can change. This is misleading, so here is some code

struct VarHdr {
    int size;
}

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

Then it is used in other structures like this.

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

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

, , , "VAR", .

+3
1

factory, , .

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

ctypes - Python () , .

(untested) :

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

Source: https://habr.com/ru/post/1757899/


All Articles