Dan Albert | 287553d | 2017-02-16 10:47:51 -0800 | [diff] [blame] | 1 | import unittest |
| 2 | from ctypes import * |
| 3 | |
| 4 | class MyInt(c_int): |
| 5 | def __cmp__(self, other): |
| 6 | if type(other) != MyInt: |
| 7 | return -1 |
| 8 | return cmp(self.value, other.value) |
| 9 | def __hash__(self): # Silence Py3k warning |
| 10 | return hash(self.value) |
| 11 | |
| 12 | class Test(unittest.TestCase): |
| 13 | |
| 14 | def test_compare(self): |
| 15 | self.assertEqual(MyInt(3), MyInt(3)) |
| 16 | self.assertNotEqual(MyInt(42), MyInt(43)) |
| 17 | |
| 18 | def test_ignore_retval(self): |
| 19 | # Test if the return value of a callback is ignored |
| 20 | # if restype is None |
| 21 | proto = CFUNCTYPE(None) |
| 22 | def func(): |
| 23 | return (1, "abc", None) |
| 24 | |
| 25 | cb = proto(func) |
| 26 | self.assertEqual(None, cb()) |
| 27 | |
| 28 | |
| 29 | def test_int_callback(self): |
| 30 | args = [] |
| 31 | def func(arg): |
| 32 | args.append(arg) |
| 33 | return arg |
| 34 | |
| 35 | cb = CFUNCTYPE(None, MyInt)(func) |
| 36 | |
| 37 | self.assertEqual(None, cb(42)) |
| 38 | self.assertEqual(type(args[-1]), MyInt) |
| 39 | |
| 40 | cb = CFUNCTYPE(c_int, c_int)(func) |
| 41 | |
| 42 | self.assertEqual(42, cb(42)) |
| 43 | self.assertEqual(type(args[-1]), int) |
| 44 | |
| 45 | def test_int_struct(self): |
| 46 | class X(Structure): |
| 47 | _fields_ = [("x", MyInt)] |
| 48 | |
| 49 | self.assertEqual(X().x, MyInt()) |
| 50 | |
| 51 | s = X() |
| 52 | s.x = MyInt(42) |
| 53 | |
| 54 | self.assertEqual(s.x, MyInt(42)) |
| 55 | |
| 56 | if __name__ == "__main__": |
| 57 | unittest.main() |