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