1 | n/a | r''' |
---|
2 | n/a | This tests the '_objects' attribute of ctypes instances. '_objects' |
---|
3 | n/a | holds references to objects that must be kept alive as long as the |
---|
4 | n/a | ctypes instance, to make sure that the memory buffer is valid. |
---|
5 | n/a | |
---|
6 | n/a | WARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself, |
---|
7 | n/a | it MUST NEVER BE MODIFIED! |
---|
8 | n/a | |
---|
9 | n/a | '_objects' is initialized to a dictionary on first use, before that it |
---|
10 | n/a | is None. |
---|
11 | n/a | |
---|
12 | n/a | Here is an array of string pointers: |
---|
13 | n/a | |
---|
14 | n/a | >>> from ctypes import * |
---|
15 | n/a | >>> array = (c_char_p * 5)() |
---|
16 | n/a | >>> print(array._objects) |
---|
17 | n/a | None |
---|
18 | n/a | >>> |
---|
19 | n/a | |
---|
20 | n/a | The memory block stores pointers to strings, and the strings itself |
---|
21 | n/a | assigned from Python must be kept. |
---|
22 | n/a | |
---|
23 | n/a | >>> array[4] = b'foo bar' |
---|
24 | n/a | >>> array._objects |
---|
25 | n/a | {'4': b'foo bar'} |
---|
26 | n/a | >>> array[4] |
---|
27 | n/a | b'foo bar' |
---|
28 | n/a | >>> |
---|
29 | n/a | |
---|
30 | n/a | It gets more complicated when the ctypes instance itself is contained |
---|
31 | n/a | in a 'base' object. |
---|
32 | n/a | |
---|
33 | n/a | >>> class X(Structure): |
---|
34 | n/a | ... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)] |
---|
35 | n/a | ... |
---|
36 | n/a | >>> x = X() |
---|
37 | n/a | >>> print(x._objects) |
---|
38 | n/a | None |
---|
39 | n/a | >>> |
---|
40 | n/a | |
---|
41 | n/a | The'array' attribute of the 'x' object shares part of the memory buffer |
---|
42 | n/a | of 'x' ('_b_base_' is either None, or the root object owning the memory block): |
---|
43 | n/a | |
---|
44 | n/a | >>> print(x.array._b_base_) # doctest: +ELLIPSIS |
---|
45 | n/a | <ctypes.test.test_objects.X object at 0x...> |
---|
46 | n/a | >>> |
---|
47 | n/a | |
---|
48 | n/a | >>> x.array[0] = b'spam spam spam' |
---|
49 | n/a | >>> x._objects |
---|
50 | n/a | {'0:2': b'spam spam spam'} |
---|
51 | n/a | >>> x.array._b_base_._objects |
---|
52 | n/a | {'0:2': b'spam spam spam'} |
---|
53 | n/a | >>> |
---|
54 | n/a | |
---|
55 | n/a | ''' |
---|
56 | n/a | |
---|
57 | n/a | import unittest, doctest |
---|
58 | n/a | |
---|
59 | n/a | import ctypes.test.test_objects |
---|
60 | n/a | |
---|
61 | n/a | class TestCase(unittest.TestCase): |
---|
62 | n/a | def test(self): |
---|
63 | n/a | failures, tests = doctest.testmod(ctypes.test.test_objects) |
---|
64 | n/a | self.assertFalse(failures, 'doctests failed, see output above') |
---|
65 | n/a | |
---|
66 | n/a | if __name__ == '__main__': |
---|
67 | n/a | doctest.testmod(ctypes.test.test_objects) |
---|