FAQ: how to vary the byte offset of a field of a ctypes.Structure
Thomas Heller
theller at ctypes.org
Thu May 31 15:48:39 EDT 2007
p.lavarre at ieee.org schrieb:
> How do I vary the byte offset of a field of a ctypes.Structure?
>
> How do I "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"?
>
> \\\
>
> For example, suppose sometimes I receive the value '\x03hi' + \x04bye'
> for the struct:
>
> class Struct34(ctypes.Structure):
> _pack_ = 1
> _fields_ = [('first', 3 * ctypes.c_ubyte),
> ('second', 4 * ctypes.c_ubyte)]
>
> but then sometimes instead I receive the value '\x05left' + \x06right'
> for the struct:
>
> class Struct56(ctypes.Structure):
> _pack_ = 1
> _fields_ = [('first', 5 * ctypes.c_ubyte),
> ('second', 6 * ctypes.c_ubyte)]
>
> Thus in general I receive (0xFF ** 2) possible combinations of field
> lengths.
>
> ///
>
> How do I declare all those hugely many simply regular combinations as
> one CTypes.structure?
>
> I also need to do series of 3 or 4 or 5 strings, not just 2 strings.
> But always the byte offsets of the subsequent fields vary when the
> byte sizes of the preceding fields vary. The byte size of the
> enclosing packed struct varies as the length of the packed bytes it
> contains.
Often it helps to ask yourself the question: How would I do this in C?
IMO, the answer to this question, applied to your problem, would be:
*Not* by using a structure. A structure is fine if the definition is fixed,
or at most has *one* variable sized field at the very end. Nothing
is true for your problem.
Thomas
More information about the Python-list
mailing list