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