/Lib/ctypes/test/test_stringptr.py

http://unladen-swallow.googlecode.com/ · Python · 75 lines · 46 code · 16 blank · 13 comment · 2 complexity · 17a868b119271131af103b43fc0e1022 MD5 · raw file

  1. import unittest
  2. from ctypes import *
  3. import _ctypes_test
  4. lib = CDLL(_ctypes_test.__file__)
  5. class StringPtrTestCase(unittest.TestCase):
  6. def test__POINTER_c_char(self):
  7. class X(Structure):
  8. _fields_ = [("str", POINTER(c_char))]
  9. x = X()
  10. # NULL pointer access
  11. self.assertRaises(ValueError, getattr, x.str, "contents")
  12. b = c_buffer("Hello, World")
  13. from sys import getrefcount as grc
  14. self.failUnlessEqual(grc(b), 2)
  15. x.str = b
  16. self.failUnlessEqual(grc(b), 3)
  17. # POINTER(c_char) and Python string is NOT compatible
  18. # POINTER(c_char) and c_buffer() is compatible
  19. for i in range(len(b)):
  20. self.failUnlessEqual(b[i], x.str[i])
  21. self.assertRaises(TypeError, setattr, x, "str", "Hello, World")
  22. def test__c_char_p(self):
  23. class X(Structure):
  24. _fields_ = [("str", c_char_p)]
  25. x = X()
  26. # c_char_p and Python string is compatible
  27. # c_char_p and c_buffer is NOT compatible
  28. self.failUnlessEqual(x.str, None)
  29. x.str = "Hello, World"
  30. self.failUnlessEqual(x.str, "Hello, World")
  31. b = c_buffer("Hello, World")
  32. self.failUnlessRaises(TypeError, setattr, x, "str", b)
  33. def test_functions(self):
  34. strchr = lib.my_strchr
  35. strchr.restype = c_char_p
  36. # c_char_p and Python string is compatible
  37. # c_char_p and c_buffer are now compatible
  38. strchr.argtypes = c_char_p, c_char
  39. self.failUnlessEqual(strchr("abcdef", "c"), "cdef")
  40. self.failUnlessEqual(strchr(c_buffer("abcdef"), "c"), "cdef")
  41. # POINTER(c_char) and Python string is NOT compatible
  42. # POINTER(c_char) and c_buffer() is compatible
  43. strchr.argtypes = POINTER(c_char), c_char
  44. buf = c_buffer("abcdef")
  45. self.failUnlessEqual(strchr(buf, "c"), "cdef")
  46. self.failUnlessEqual(strchr("abcdef", "c"), "cdef")
  47. # XXX These calls are dangerous, because the first argument
  48. # to strchr is no longer valid after the function returns!
  49. # So we must keep a reference to buf separately
  50. strchr.restype = POINTER(c_char)
  51. buf = c_buffer("abcdef")
  52. r = strchr(buf, "c")
  53. x = r[0], r[1], r[2], r[3], r[4]
  54. self.failUnlessEqual(x, ("c", "d", "e", "f", "\000"))
  55. del buf
  56. # x1 will NOT be the same as x, usually:
  57. x1 = r[0], r[1], r[2], r[3], r[4]
  58. if __name__ == '__main__':
  59. unittest.main()