| 1 |
import unittest |
| 2 |
from test import support |
| 3 |
import ctypes |
| 4 |
import gc |
| 5 |
|
| 6 |
MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) |
| 7 |
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong) |
| 8 |
|
| 9 |
import _ctypes_test |
| 10 |
dll = ctypes.CDLL(_ctypes_test.__file__) |
| 11 |
|
| 12 |
class RefcountTestCase(unittest.TestCase): |
| 13 |
|
| 14 |
@support.refcount_test |
| 15 |
def test_1(self): |
| 16 |
from sys import getrefcount as grc |
| 17 |
|
| 18 |
f = dll._testfunc_callback_i_if |
| 19 |
f.restype = ctypes.c_int |
| 20 |
f.argtypes = [ctypes.c_int, MyCallback] |
| 21 |
|
| 22 |
def callback(value): |
| 23 |
|
| 24 |
return value |
| 25 |
|
| 26 |
self.assertEqual(grc(callback), 2) |
| 27 |
cb = MyCallback(callback) |
| 28 |
|
| 29 |
self.assertGreater(grc(callback), 2) |
| 30 |
result = f(-10, cb) |
| 31 |
self.assertEqual(result, -18) |
| 32 |
cb = None |
| 33 |
|
| 34 |
gc.collect() |
| 35 |
|
| 36 |
self.assertEqual(grc(callback), 2) |
| 37 |
|
| 38 |
|
| 39 |
@support.refcount_test |
| 40 |
def test_refcount(self): |
| 41 |
from sys import getrefcount as grc |
| 42 |
def func(*args): |
| 43 |
pass |
| 44 |
|
| 45 |
self.assertEqual(grc(func), 2) |
| 46 |
|
| 47 |
|
| 48 |
f = OtherCallback(func) |
| 49 |
self.assertGreater(grc(func), 2) |
| 50 |
|
| 51 |
|
| 52 |
del f |
| 53 |
self.assertGreaterEqual(grc(func), 2) |
| 54 |
|
| 55 |
|
| 56 |
gc.collect() |
| 57 |
self.assertEqual(grc(func), 2) |
| 58 |
|
| 59 |
class X(ctypes.Structure): |
| 60 |
_fields_ = [("a", OtherCallback)] |
| 61 |
x = X() |
| 62 |
x.a = OtherCallback(func) |
| 63 |
|
| 64 |
|
| 65 |
self.assertGreater(grc(func), 2) |
| 66 |
|
| 67 |
|
| 68 |
del x |
| 69 |
self.assertGreaterEqual(grc(func), 2) |
| 70 |
|
| 71 |
|
| 72 |
gc.collect() |
| 73 |
self.assertEqual(grc(func), 2) |
| 74 |
|
| 75 |
f = OtherCallback(func) |
| 76 |
|
| 77 |
|
| 78 |
self.assertGreater(grc(func), 2) |
| 79 |
|
| 80 |
|
| 81 |
f.cycle = f |
| 82 |
|
| 83 |
del f |
| 84 |
gc.collect() |
| 85 |
self.assertEqual(grc(func), 2) |
| 86 |
|
| 87 |
class AnotherLeak(unittest.TestCase): |
| 88 |
@support.refcount_test |
| 89 |
def test_callback(self): |
| 90 |
import sys |
| 91 |
|
| 92 |
proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) |
| 93 |
def func(a, b): |
| 94 |
return a * b * 2 |
| 95 |
f = proto(func) |
| 96 |
|
| 97 |
a = sys.getrefcount(ctypes.c_int) |
| 98 |
f(1, 2) |
| 99 |
self.assertEqual(sys.getrefcount(ctypes.c_int), a) |
| 100 |
|
| 101 |
@support.refcount_test |
| 102 |
def test_callback_py_object_none_return(self): |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
for FUNCTYPE in (ctypes.CFUNCTYPE, ctypes.PYFUNCTYPE): |
| 107 |
with self.subTest(FUNCTYPE=FUNCTYPE): |
| 108 |
@FUNCTYPE(ctypes.py_object) |
| 109 |
def func(): |
| 110 |
return None |
| 111 |
|
| 112 |
|
| 113 |
for _ in range(10000): |
| 114 |
func() |
| 115 |
|
| 116 |
if __name__ == '__main__': |
| 117 |
unittest.main() |