1 ######################################################################
2 # This file should be kept compatible with Python 2.3, see PEP 291. #
3 ######################################################################
7 _array_type
= type(c_int
* 3)
9 def _other_endian(typ
):
10 """Return the type with the 'other' byte order. Simple types like
11 c_int and so on already have __ctype_be__ and __ctype_le__
12 attributes which contain the types, for more complicated types
13 only arrays are supported.
16 return getattr(typ
, _OTHER_ENDIAN
)
17 except AttributeError:
18 if type(typ
) == _array_type
:
19 return _other_endian(typ
._type
_) * typ
._length
_
20 raise TypeError("This type does not support other endian: %s" % typ
)
22 class _swapped_meta(type(Structure
)):
23 def __setattr__(self
, attrname
, value
):
24 if attrname
== "_fields_":
30 fields
.append((name
, _other_endian(typ
)) + rest
)
32 super(_swapped_meta
, self
).__setattr
__(attrname
, value
)
34 ################################################################
36 # Note: The Structure metaclass checks for the *presence* (not the
37 # value!) of a _swapped_bytes_ attribute to determine the bit order in
38 # structures containing bit fields.
40 if sys
.byteorder
== "little":
41 _OTHER_ENDIAN
= "__ctype_be__"
43 LittleEndianStructure
= Structure
45 class BigEndianStructure(Structure
):
46 """Structure with big endian byte order"""
47 __metaclass__
= _swapped_meta
50 elif sys
.byteorder
== "big":
51 _OTHER_ENDIAN
= "__ctype_le__"
53 BigEndianStructure
= Structure
54 class LittleEndianStructure(Structure
):
55 """Structure with little endian byte order"""
56 __metaclass__
= _swapped_meta
60 raise RuntimeError("Invalid byteorder")