/Lib/ctypes/test/test_objects.py

http://unladen-swallow.googlecode.com/ · Python · 70 lines · 63 code · 4 blank · 3 comment · 3 complexity · ffb2f5a9ba99acdfffcc7ce85727c8cd MD5 · raw file

  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. WARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself,
  6. it MUST NEVER BE MODIFIED!
  7. '_objects' is initialized to a dictionary on first use, before that it
  8. is None.
  9. Here is an array of string pointers:
  10. >>> from ctypes import *
  11. >>> array = (c_char_p * 5)()
  12. >>> print array._objects
  13. None
  14. >>>
  15. The memory block stores pointers to strings, and the strings itself
  16. assigned from Python must be kept.
  17. >>> array[4] = 'foo bar'
  18. >>> array._objects
  19. {'4': 'foo bar'}
  20. >>> array[4]
  21. 'foo bar'
  22. >>>
  23. It gets more complicated when the ctypes instance itself is contained
  24. in a 'base' object.
  25. >>> class X(Structure):
  26. ... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)]
  27. ...
  28. >>> x = X()
  29. >>> print x._objects
  30. None
  31. >>>
  32. The'array' attribute of the 'x' object shares part of the memory buffer
  33. of 'x' ('_b_base_' is either None, or the root object owning the memory block):
  34. >>> print x.array._b_base_ # doctest: +ELLIPSIS
  35. <ctypes.test.test_objects.X object at 0x...>
  36. >>>
  37. >>> x.array[0] = 'spam spam spam'
  38. >>> x._objects
  39. {'0:2': 'spam spam spam'}
  40. >>> x.array._b_base_._objects
  41. {'0:2': 'spam spam spam'}
  42. >>>
  43. '''
  44. import unittest, doctest, sys
  45. import ctypes.test.test_objects
  46. class TestCase(unittest.TestCase):
  47. if sys.hexversion > 0x02040000:
  48. # Python 2.3 has no ELLIPSIS flag, so we don't test with this
  49. # version:
  50. def test(self):
  51. doctest.testmod(ctypes.test.test_objects)
  52. if __name__ == '__main__':
  53. if sys.hexversion > 0x02040000:
  54. doctest.testmod(ctypes.test.test_objects)