1 import unittest 2 from ctypes import * 3 from binascii import hexlify 4 import re 5 6 def dump(obj): 7 # helper function to dump memory contents in hex, with a hyphen 8 # between the bytes. 9 h = hexlify(memoryview(obj)) 10 return re.sub(r"(..)", r"\1-", h)[:-1] 11 12 13 class Value(Structure): 14 _fields_ = [("val", c_byte)] 15 16 class Container(Structure): 17 _fields_ = [("pvalues", POINTER(Value))] 18 19 class 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 63 if __name__ == "__main__": 64 unittest.main() 65