uctypes.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """
  2. uctypes 模块用来访问二进制数据结构,它提供 C 兼容的数据类型。
  3. """
  4. LITTLE_ENDIAN = ... # type: int
  5. BIG_ENDIAN = ... # type: int
  6. NATIVE = ... # type: int
  7. class struct(addr, descriptor, type):
  8. """
  9. 将内存中以 c 形式打包的结构体或联合体转换为字典,并返回该字典。
  10. - addr:开始转换的地址
  11. - descriptor:转换描述符
  12. 格式:"field_name":offset|uctypes.UINT32
  13. - offset:偏移量,
  14. 单位:字节、VOID、UINT8、INT8、UINT16、INT16、UINT32、INT32、UINT64、INT64、BFUINT8、BFINT8、BFUINT16、BFINT16、BFUINT32、BFINT32、BF_POS、BF_LEN、FLOAT32、FLOAT64、PTR、ARRAY
  15. - type:c 结构体或联合体存储类型,默认为本地存储类型
  16. 示例:
  17. - a = b"0123"
  18. - s = uctypes.struct(uctypes.addressof(a), {"a": uctypes.UINT8 | 0, "b": uctypes.UINT16 | 1}, uctypes.LITTLE_ENDIAN)
  19. - print(s)
  20. - <struct STRUCT 3ffc7360>
  21. - print(s.a)
  22. - 48
  23. - s.a = 49
  24. - print(a)
  25. - b'1123'
  26. """
  27. def __init__(self) -> None:
  28. ...
  29. def sizeof(self, struct) -> None:
  30. """
  31. 按字节返回数据的大小。参数可以是类或者数据对象 (或集合)。 示例:
  32. - a = b"0123"
  33. - b = uctypes.struct(uctypes.addressof(a), {"a": uctypes.UINT8 | 0, "b": uctypes.UINT16 | 1}, uctypes.LITTLE_ENDIAN)
  34. - b.a
  35. - 48
  36. - print(uctypes.sizeof(b))
  37. - 3
  38. """
  39. ...
  40. def addressof(self, obj) -> None:
  41. """
  42. 返回对象地址。参数需要是 bytes, bytearray 。 示例:
  43. - a = b"0123"
  44. - print(uctypes.addressof(a))
  45. - 1073504048
  46. """
  47. ...
  48. def bytes_at(self, addr, size)-> None:
  49. """
  50. 捕捉从 addr 开始到 size 个地址偏移量结束的内存数据为 bytearray 对象并返回。 示例:
  51. - a = b"0123"
  52. - print( uctypes.bytes_at(uctypes.addressof(a), 4))
  53. - b'0123'
  54. """
  55. ...
  56. def bytearray_at(self, addr, size) -> None:
  57. """
  58. 捕捉给定大小和地址内存为 bytearray 对象。与 bytes_at() 函数不同的是,它可以被再次写入,可以访问给定地址的参数。 示例:
  59. - a = b"0123"
  60. - print(uctypes.bytearray_at(uctypes.addressof(a), 2))
  61. - bytearray(b'01')
  62. """
  63. ...