1 | n/a | import unittest |
---|
2 | n/a | from ctypes import * |
---|
3 | n/a | from binascii import hexlify |
---|
4 | n/a | import re |
---|
5 | n/a | |
---|
6 | n/a | def dump(obj): |
---|
7 | n/a | # helper function to dump memory contents in hex, with a hyphen |
---|
8 | n/a | # between the bytes. |
---|
9 | n/a | h = hexlify(memoryview(obj)).decode() |
---|
10 | n/a | return re.sub(r"(..)", r"\1-", h)[:-1] |
---|
11 | n/a | |
---|
12 | n/a | |
---|
13 | n/a | class Value(Structure): |
---|
14 | n/a | _fields_ = [("val", c_byte)] |
---|
15 | n/a | |
---|
16 | n/a | class Container(Structure): |
---|
17 | n/a | _fields_ = [("pvalues", POINTER(Value))] |
---|
18 | n/a | |
---|
19 | n/a | class Test(unittest.TestCase): |
---|
20 | n/a | def test(self): |
---|
21 | n/a | # create an array of 4 values |
---|
22 | n/a | val_array = (Value * 4)() |
---|
23 | n/a | |
---|
24 | n/a | # create a container, which holds a pointer to the pvalues array. |
---|
25 | n/a | c = Container() |
---|
26 | n/a | c.pvalues = val_array |
---|
27 | n/a | |
---|
28 | n/a | # memory contains 4 NUL bytes now, that's correct |
---|
29 | n/a | self.assertEqual("00-00-00-00", dump(val_array)) |
---|
30 | n/a | |
---|
31 | n/a | # set the values of the array through the pointer: |
---|
32 | n/a | for i in range(4): |
---|
33 | n/a | c.pvalues[i].val = i + 1 |
---|
34 | n/a | |
---|
35 | n/a | values = [c.pvalues[i].val for i in range(4)] |
---|
36 | n/a | |
---|
37 | n/a | # These are the expected results: here s the bug! |
---|
38 | n/a | self.assertEqual( |
---|
39 | n/a | (values, dump(val_array)), |
---|
40 | n/a | ([1, 2, 3, 4], "01-02-03-04") |
---|
41 | n/a | ) |
---|
42 | n/a | |
---|
43 | n/a | def test_2(self): |
---|
44 | n/a | |
---|
45 | n/a | val_array = (Value * 4)() |
---|
46 | n/a | |
---|
47 | n/a | # memory contains 4 NUL bytes now, that's correct |
---|
48 | n/a | self.assertEqual("00-00-00-00", dump(val_array)) |
---|
49 | n/a | |
---|
50 | n/a | ptr = cast(val_array, POINTER(Value)) |
---|
51 | n/a | # set the values of the array through the pointer: |
---|
52 | n/a | for i in range(4): |
---|
53 | n/a | ptr[i].val = i + 1 |
---|
54 | n/a | |
---|
55 | n/a | values = [ptr[i].val for i in range(4)] |
---|
56 | n/a | |
---|
57 | n/a | # These are the expected results: here s the bug! |
---|
58 | n/a | self.assertEqual( |
---|
59 | n/a | (values, dump(val_array)), |
---|
60 | n/a | ([1, 2, 3, 4], "01-02-03-04") |
---|
61 | n/a | ) |
---|
62 | n/a | |
---|
63 | n/a | if __name__ == "__main__": |
---|
64 | n/a | unittest.main() |
---|