/Lib/ctypes/test/test_returnfuncptrs.py

http://unladen-swallow.googlecode.com/ · Python · 35 lines · 25 code · 5 blank · 5 comment · 1 complexity · 597b7359290e78f360311c0cc57c73f5 MD5 · raw file

  1. import unittest
  2. from ctypes import *
  3. import _ctypes_test
  4. class ReturnFuncPtrTestCase(unittest.TestCase):
  5. def test_with_prototype(self):
  6. # The _ctypes_test shared lib/dll exports quite some functions for testing.
  7. # The get_strchr function returns a *pointer* to the C strchr function.
  8. dll = CDLL(_ctypes_test.__file__)
  9. get_strchr = dll.get_strchr
  10. get_strchr.restype = CFUNCTYPE(c_char_p, c_char_p, c_char)
  11. strchr = get_strchr()
  12. self.failUnlessEqual(strchr("abcdef", "b"), "bcdef")
  13. self.failUnlessEqual(strchr("abcdef", "x"), None)
  14. self.assertRaises(ArgumentError, strchr, "abcdef", 3)
  15. self.assertRaises(TypeError, strchr, "abcdef")
  16. def test_without_prototype(self):
  17. dll = CDLL(_ctypes_test.__file__)
  18. get_strchr = dll.get_strchr
  19. # the default 'c_int' would not work on systems where sizeof(int) != sizeof(void *)
  20. get_strchr.restype = c_void_p
  21. addr = get_strchr()
  22. # _CFuncPtr instances are now callable with an integer argument
  23. # which denotes a function address:
  24. strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr)
  25. self.failUnless(strchr("abcdef", "b"), "bcdef")
  26. self.failUnlessEqual(strchr("abcdef", "x"), None)
  27. self.assertRaises(ArgumentError, strchr, "abcdef", 3)
  28. self.assertRaises(TypeError, strchr, "abcdef")
  29. if __name__ == "__main__":
  30. unittest.main()