blob: b48bda5c4f20acd0002d4b98b5429351a4d505e7 [file] [log] [blame]
Thomas Hellerbabddfc2006-03-08 19:56:54 +00001import sys
2from ctypes import *
3
4_array_type = type(c_int * 3)
5
6def _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
19class _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 Rossumcd16bf62007-06-13 18:07:49 +000029 super().__setattr__(attrname, value)
Thomas Hellerbabddfc2006-03-08 19:56:54 +000030
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
37if sys.byteorder == "little":
38 _OTHER_ENDIAN = "__ctype_be__"
39
40 LittleEndianStructure = Structure
41
Guido van Rossum52cc1d82007-03-18 15:41:51 +000042 class BigEndianStructure(Structure, metaclass=_swapped_meta):
Thomas Hellerbabddfc2006-03-08 19:56:54 +000043 """Structure with big endian byte order"""
Thomas Hellerbabddfc2006-03-08 19:56:54 +000044 _swappedbytes_ = None
45
46elif sys.byteorder == "big":
47 _OTHER_ENDIAN = "__ctype_le__"
48
49 BigEndianStructure = Structure
Guido van Rossum52cc1d82007-03-18 15:41:51 +000050 class LittleEndianStructure(Structure, metaclass=_swapped_meta):
Thomas Hellerbabddfc2006-03-08 19:56:54 +000051 """Structure with little endian byte order"""
Thomas Hellerbabddfc2006-03-08 19:56:54 +000052 _swappedbytes_ = None
53
54else:
55 raise RuntimeError("Invalid byteorder")