blob: 19e3dc1f2d7621d687b2c6c126c8bd6d5bdb10da [file] [log] [blame]
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001r'''
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)()
Guido van Rossum7131f842007-02-09 20:13:25 +000016>>> print(array._objects)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017None
18>>>
19
20The memory block stores pointers to strings, and the strings itself
21assigned from Python must be kept.
22
Victor Stinner42746df2010-07-27 23:36:41 +000023>>> array[4] = b'foo bar'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024>>> array._objects
Thomas Hellerf7c6d862007-07-12 13:55:37 +000025{'4': b'foo bar'}
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026>>> array[4]
Thomas Heller8b939522009-09-04 18:24:41 +000027b'foo bar'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028>>>
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()
Guido van Rossum7131f842007-02-09 20:13:25 +000037>>> print(x._objects)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000038None
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
Guido van Rossum7131f842007-02-09 20:13:25 +000044>>> print(x.array._b_base_) # doctest: +ELLIPSIS
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045<ctypes.test.test_objects.X object at 0x...>
46>>>
47
Victor Stinner42746df2010-07-27 23:36:41 +000048>>> x.array[0] = b'spam spam spam'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049>>> x._objects
Thomas Hellerf7c6d862007-07-12 13:55:37 +000050{'0:2': b'spam spam spam'}
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051>>> x.array._b_base_._objects
Thomas Hellerf7c6d862007-07-12 13:55:37 +000052{'0:2': b'spam spam spam'}
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053>>>
54
55'''
56
Berker Peksag1e8ee9b2016-04-24 07:31:42 +030057import unittest, doctest
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058
59import ctypes.test.test_objects
60
61class TestCase(unittest.TestCase):
Zachary Ware9422df02014-06-13 13:44:39 -050062 def test(self):
63 failures, tests = doctest.testmod(ctypes.test.test_objects)
64 self.assertFalse(failures, 'doctests failed, see output above')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065
66if __name__ == '__main__':
Zachary Ware9422df02014-06-13 13:44:39 -050067 doctest.testmod(ctypes.test.test_objects)