| 1 | n/a | import sys |
|---|
| 2 | n/a | from ctypes import * |
|---|
| 3 | n/a | |
|---|
| 4 | n/a | _array_type = type(Array) |
|---|
| 5 | n/a | |
|---|
| 6 | n/a | def _other_endian(typ): |
|---|
| 7 | n/a | """Return the type with the 'other' byte order. Simple types like |
|---|
| 8 | n/a | c_int and so on already have __ctype_be__ and __ctype_le__ |
|---|
| 9 | n/a | attributes which contain the types, for more complicated types |
|---|
| 10 | n/a | arrays and structures are supported. |
|---|
| 11 | n/a | """ |
|---|
| 12 | n/a | # check _OTHER_ENDIAN attribute (present if typ is primitive type) |
|---|
| 13 | n/a | if hasattr(typ, _OTHER_ENDIAN): |
|---|
| 14 | n/a | return getattr(typ, _OTHER_ENDIAN) |
|---|
| 15 | n/a | # if typ is array |
|---|
| 16 | n/a | if isinstance(typ, _array_type): |
|---|
| 17 | n/a | return _other_endian(typ._type_) * typ._length_ |
|---|
| 18 | n/a | # if typ is structure |
|---|
| 19 | n/a | if issubclass(typ, Structure): |
|---|
| 20 | n/a | return typ |
|---|
| 21 | n/a | raise TypeError("This type does not support other endian: %s" % typ) |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | class _swapped_meta(type(Structure)): |
|---|
| 24 | n/a | def __setattr__(self, attrname, value): |
|---|
| 25 | n/a | if attrname == "_fields_": |
|---|
| 26 | n/a | fields = [] |
|---|
| 27 | n/a | for desc in value: |
|---|
| 28 | n/a | name = desc[0] |
|---|
| 29 | n/a | typ = desc[1] |
|---|
| 30 | n/a | rest = desc[2:] |
|---|
| 31 | n/a | fields.append((name, _other_endian(typ)) + rest) |
|---|
| 32 | n/a | value = fields |
|---|
| 33 | n/a | super().__setattr__(attrname, value) |
|---|
| 34 | n/a | |
|---|
| 35 | n/a | ################################################################ |
|---|
| 36 | n/a | |
|---|
| 37 | n/a | # Note: The Structure metaclass checks for the *presence* (not the |
|---|
| 38 | n/a | # value!) of a _swapped_bytes_ attribute to determine the bit order in |
|---|
| 39 | n/a | # structures containing bit fields. |
|---|
| 40 | n/a | |
|---|
| 41 | n/a | if sys.byteorder == "little": |
|---|
| 42 | n/a | _OTHER_ENDIAN = "__ctype_be__" |
|---|
| 43 | n/a | |
|---|
| 44 | n/a | LittleEndianStructure = Structure |
|---|
| 45 | n/a | |
|---|
| 46 | n/a | class BigEndianStructure(Structure, metaclass=_swapped_meta): |
|---|
| 47 | n/a | """Structure with big endian byte order""" |
|---|
| 48 | n/a | __slots__ = () |
|---|
| 49 | n/a | _swappedbytes_ = None |
|---|
| 50 | n/a | |
|---|
| 51 | n/a | elif sys.byteorder == "big": |
|---|
| 52 | n/a | _OTHER_ENDIAN = "__ctype_le__" |
|---|
| 53 | n/a | |
|---|
| 54 | n/a | BigEndianStructure = Structure |
|---|
| 55 | n/a | class LittleEndianStructure(Structure, metaclass=_swapped_meta): |
|---|
| 56 | n/a | """Structure with little endian byte order""" |
|---|
| 57 | n/a | __slots__ = () |
|---|
| 58 | n/a | _swappedbytes_ = None |
|---|
| 59 | n/a | |
|---|
| 60 | n/a | else: |
|---|
| 61 | n/a | raise RuntimeError("Invalid byteorder") |
|---|