|
| 1 | +# This test is exactly like uctypes_le.py, but uses native structure layout. |
| 2 | +# Codepaths for packed vs native structures are different. This test only works |
| 3 | +# on little-endian machine (no matter if 32 or 64 bit). |
| 4 | +import sys |
| 5 | +import uctypes |
| 6 | + |
| 7 | +if sys.byteorder != "little": |
| 8 | + print("SKIP") |
| 9 | + sys.exit() |
| 10 | + |
| 11 | + |
| 12 | +desc = { |
| 13 | + "s0": uctypes.UINT16 | 0, |
| 14 | + "sub": (0, { |
| 15 | + "b0": uctypes.UINT8 | 0, |
| 16 | + "b1": uctypes.UINT8 | 1, |
| 17 | + }), |
| 18 | + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), |
| 19 | + "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), |
| 20 | + "bitf0": uctypes.BFUINT16 | 0 | 0 << 17 | 8 << 22, |
| 21 | + "bitf1": uctypes.BFUINT16 | 0 | 8 << 17 | 8 << 22, |
| 22 | + |
| 23 | + "bf0": uctypes.BFUINT16 | 0 | 0 << 17 | 4 << 22, |
| 24 | + "bf1": uctypes.BFUINT16 | 0 | 4 << 17 | 4 << 22, |
| 25 | + "bf2": uctypes.BFUINT16 | 0 | 8 << 17 | 4 << 22, |
| 26 | + "bf3": uctypes.BFUINT16 | 0 | 12 << 17 | 4 << 22, |
| 27 | + |
| 28 | + "ptr": (uctypes.PTR | 0, uctypes.UINT8), |
| 29 | + "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), |
| 30 | +} |
| 31 | + |
| 32 | +data = bytearray(b"01") |
| 33 | + |
| 34 | +S = uctypes.struct(desc, uctypes.addressof(data), uctypes.NATIVE) |
| 35 | + |
| 36 | +#print(S) |
| 37 | +print(hex(S.s0)) |
| 38 | +assert hex(S.s0) == "0x3130" |
| 39 | +#print(S.sub.b0) |
| 40 | +print(S.sub.b0, S.sub.b1) |
| 41 | +assert S.sub.b0, S.sub.b1 == (0x30, 0x31) |
| 42 | + |
| 43 | +try: |
| 44 | + S[0] |
| 45 | + assert False, "Can't index struct" |
| 46 | +except TypeError: |
| 47 | + print("TypeError") |
| 48 | + |
| 49 | +print("arr:", S.arr[0], S.arr[1]) |
| 50 | +assert (S.arr[0], S.arr[1]) == (0x30, 0x31) |
| 51 | + |
| 52 | +print("arr of struct:", S.arr2[0].b, S.arr2[1].b) |
| 53 | +assert (S.arr2[0].b, S.arr2[1].b) == (0x30, 0x31) |
| 54 | + |
| 55 | + |
| 56 | +try: |
| 57 | + S.arr[2] |
| 58 | + assert False, "Out of bounds index" |
| 59 | +except IndexError: |
| 60 | + print("IndexError") |
| 61 | + |
| 62 | +print("bf:", S.bitf0, S.bitf1) |
| 63 | +assert (S.bitf0, S.bitf1) == (0x30, 0x31) |
| 64 | + |
| 65 | +print("bf 4bit:", S.bf3, S.bf2, S.bf1, S.bf0) |
| 66 | +assert (S.bf3, S.bf2, S.bf1, S.bf0) == (3, 1, 3, 0) |
| 67 | + |
| 68 | +# Write access |
| 69 | + |
| 70 | +S.sub.b0 = ord("2") |
| 71 | +print(data) |
| 72 | +assert bytes(data) == b"21" |
| 73 | + |
| 74 | +S.bf3 = 5 |
| 75 | +print(data) |
| 76 | +assert bytes(data) == b"2Q" |
0 commit comments