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