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