summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorYukihiro Nakadaira <yukihiro.nakadaira@gmail.com>2023-01-26 08:28:34 (GMT)
committerGitHub <noreply@github.com>2023-01-26 08:28:34 (GMT)
commitdfad678d7024ab86d265d84ed45999e031a03691 (patch)
treeeb749dbc9392eb494a8b36faba1cb13ae563ae20 /Lib
parentf5ad63f79af3a5876f90b409d0c8402fa54e878a (diff)
downloadcpython-dfad678d7024ab86d265d84ed45999e031a03691.zip
cpython-dfad678d7024ab86d265d84ed45999e031a03691.tar.gz
cpython-dfad678d7024ab86d265d84ed45999e031a03691.tar.bz2
gh-99952: [ctypes] fix refcount issues in from_param() result. (#100169)
Fixes a reference counting issue with `ctypes.Structure` when a `from_param()` method call is used and the structure size is larger than a C pointer `sizeof(void*)`. This problem existed for a very long time, but became more apparent in 3.8+ by change likely due to garbage collection cleanup timing changes.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_ctypes/test_parameters.py52
1 files changed, 52 insertions, 0 deletions
diff --git a/Lib/test/test_ctypes/test_parameters.py b/Lib/test/test_ctypes/test_parameters.py
index 22d290d..06cc951 100644
--- a/Lib/test/test_ctypes/test_parameters.py
+++ b/Lib/test/test_ctypes/test_parameters.py
@@ -266,6 +266,58 @@ class SimpleTypesTestCase(unittest.TestCase):
self.assertRegex(repr(c_wchar_p.from_param('hihi')), r"^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
self.assertRegex(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
+ @test.support.cpython_only
+ def test_from_param_result_refcount(self):
+ # Issue #99952
+ import _ctypes_test
+ from ctypes import PyDLL, c_int, c_void_p, py_object, Structure
+
+ class X(Structure):
+ """This struct size is <= sizeof(void*)."""
+ _fields_ = [("a", c_void_p)]
+
+ def __del__(self):
+ trace.append(4)
+
+ @classmethod
+ def from_param(cls, value):
+ trace.append(2)
+ return cls()
+
+ PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
+ PyList_Append.restype = c_int
+ PyList_Append.argtypes = [py_object, py_object, X]
+
+ trace = []
+ trace.append(1)
+ PyList_Append(trace, 3, "dummy")
+ trace.append(5)
+
+ self.assertEqual(trace, [1, 2, 3, 4, 5])
+
+ class Y(Structure):
+ """This struct size is > sizeof(void*)."""
+ _fields_ = [("a", c_void_p), ("b", c_void_p)]
+
+ def __del__(self):
+ trace.append(4)
+
+ @classmethod
+ def from_param(cls, value):
+ trace.append(2)
+ return cls()
+
+ PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
+ PyList_Append.restype = c_int
+ PyList_Append.argtypes = [py_object, py_object, Y]
+
+ trace = []
+ trace.append(1)
+ PyList_Append(trace, 3, "dummy")
+ trace.append(5)
+
+ self.assertEqual(trace, [1, 2, 3, 4, 5])
+
################################################################
if __name__ == '__main__':