1 | n/a | import unittest |
---|
2 | n/a | from ctypes import * |
---|
3 | n/a | |
---|
4 | n/a | ################################################################ |
---|
5 | n/a | # |
---|
6 | n/a | # The incomplete pointer example from the tutorial |
---|
7 | n/a | # |
---|
8 | n/a | |
---|
9 | n/a | class MyTestCase(unittest.TestCase): |
---|
10 | n/a | |
---|
11 | n/a | def test_incomplete_example(self): |
---|
12 | n/a | lpcell = POINTER("cell") |
---|
13 | n/a | class cell(Structure): |
---|
14 | n/a | _fields_ = [("name", c_char_p), |
---|
15 | n/a | ("next", lpcell)] |
---|
16 | n/a | |
---|
17 | n/a | SetPointerType(lpcell, cell) |
---|
18 | n/a | |
---|
19 | n/a | c1 = cell() |
---|
20 | n/a | c1.name = b"foo" |
---|
21 | n/a | c2 = cell() |
---|
22 | n/a | c2.name = b"bar" |
---|
23 | n/a | |
---|
24 | n/a | c1.next = pointer(c2) |
---|
25 | n/a | c2.next = pointer(c1) |
---|
26 | n/a | |
---|
27 | n/a | p = c1 |
---|
28 | n/a | |
---|
29 | n/a | result = [] |
---|
30 | n/a | for i in range(8): |
---|
31 | n/a | result.append(p.name) |
---|
32 | n/a | p = p.next[0] |
---|
33 | n/a | self.assertEqual(result, [b"foo", b"bar"] * 4) |
---|
34 | n/a | |
---|
35 | n/a | # to not leak references, we must clean _pointer_type_cache |
---|
36 | n/a | from ctypes import _pointer_type_cache |
---|
37 | n/a | del _pointer_type_cache[cell] |
---|
38 | n/a | |
---|
39 | n/a | ################################################################ |
---|
40 | n/a | |
---|
41 | n/a | if __name__ == '__main__': |
---|
42 | n/a | unittest.main() |
---|