/Lib/ctypes/_endian.py

http://unladen-swallow.googlecode.com/ · Python · 60 lines · 55 code · 2 blank · 3 comment · 0 complexity · a7ab0a4cd69597fe26678fc2f1f27fcd MD5 · raw file

  1. ######################################################################
  2. # This file should be kept compatible with Python 2.3, see PEP 291. #
  3. ######################################################################
  4. import sys
  5. from ctypes import *
  6. _array_type = type(c_int * 3)
  7. def _other_endian(typ):
  8. """Return the type with the 'other' byte order. Simple types like
  9. c_int and so on already have __ctype_be__ and __ctype_le__
  10. attributes which contain the types, for more complicated types
  11. only arrays are supported.
  12. """
  13. try:
  14. return getattr(typ, _OTHER_ENDIAN)
  15. except AttributeError:
  16. if type(typ) == _array_type:
  17. return _other_endian(typ._type_) * typ._length_
  18. raise TypeError("This type does not support other endian: %s" % typ)
  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
  29. super(_swapped_meta, self).__setattr__(attrname, value)
  30. ################################################################
  31. # Note: The Structure metaclass checks for the *presence* (not the
  32. # value!) of a _swapped_bytes_ attribute to determine the bit order in
  33. # structures containing bit fields.
  34. if sys.byteorder == "little":
  35. _OTHER_ENDIAN = "__ctype_be__"
  36. LittleEndianStructure = Structure
  37. class BigEndianStructure(Structure):
  38. """Structure with big endian byte order"""
  39. __metaclass__ = _swapped_meta
  40. _swappedbytes_ = None
  41. elif sys.byteorder == "big":
  42. _OTHER_ENDIAN = "__ctype_le__"
  43. BigEndianStructure = Structure
  44. class LittleEndianStructure(Structure):
  45. """Structure with little endian byte order"""
  46. __metaclass__ = _swapped_meta
  47. _swappedbytes_ = None
  48. else:
  49. raise RuntimeError("Invalid byteorder")