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 * 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] = 'foo bar' 24 >>> array._objects 25 {'4': 'foo bar'} 26 >>> array[4] 27 '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 <ctypes.test.test_objects.X object at 0x...> 46 >>> 47 48 >>> x.array[0] = 'spam spam spam' 49 >>> x._objects 50 {'0:2': 'spam spam spam'} 51 >>> x.array._b_base_._objects 52 {'0:2': 'spam spam spam'} 53 >>> 54 55 ''' 56 57 import unittest, doctest, sys 58 59 import ctypes.test.test_objects 60 61 class TestCase(unittest.TestCase): 62 if sys.hexversion > 0x02040000: 63 # Python 2.3 has no ELLIPSIS flag, so we don't test with this 64 # version: 65 def test(self): 66 doctest.testmod(ctypes.test.test_objects) 67 68 if __name__ == '__main__': 69 if sys.hexversion > 0x02040000: 70 doctest.testmod(ctypes.test.test_objects) 71