How do I emulate a dynamically sized C structure in Python using ctypes
I'm writing some python code to interact with a C DLL that uses structures extensively.
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)];
}
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 in a way that the resulting struc开发者_如何学JAVAture can be passed back and forth between my pythong script and the DLL.
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-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.
(untested) Example:
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()
精彩评论