There is c struct definition
struct Matrix {
int width;
int height;
int** data;
};
How to use python’s ctypes.Struct to define it?
class Matrix( ctypes.Structure ):
_fields_ = [
( "width", ctypes.c_int ),
( "height", ctypes.c_int ),
( "data", ??? ),
]
I don’t know how to define the “data” ‘s type.
Anyone here help?
The most literal translation of
int**would be:That is, it is a pointer to a pointer to an int.
A potentially more idiomatic way is a 2D array:
, but to do that you need to know how many elements are in the array – the size is part of the type in ctypes. If, as it seems, you don’t know that size in advance (and it can change per instance of the struct), a pointer to a pointer is the best option.
To instantiate this takes a little less indirection – by the time you want to create the array, by definition you will know how big it needs to be. So, you can just do:
Which will give you a
height-length array ofwidth-length arrays ofc_int. That is, it does (broadly) the same thing as the C++ code:Or, if you prefer: