Skip to content

Commit 8f45925

Browse files
gh-144100: Fix crash for POINTER(str) used in ctypes argtypes (#144108)
Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent decb25e commit 8f45925

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

Lib/test/test_ctypes/test_pointers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,16 @@ class Cls(Structure):
403403
self.assertEqual(len(ws_typ), 0, ws_typ)
404404
self.assertEqual(len(ws_ptr), 0, ws_ptr)
405405

406+
def test_pointer_proto_missing_argtypes_error(self):
407+
class BadType(ctypes._Pointer):
408+
# _type_ is intentionally missing
409+
pass
410+
411+
func = ctypes.pythonapi.Py_GetVersion
412+
func.argtypes = (BadType,)
413+
414+
with self.assertRaises(ctypes.ArgumentError):
415+
func(object())
406416

407417
class PointerTypeCacheTestCase(unittest.TestCase):
408418
# dummy tests to check warnings and base behavior
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed a crash in ctypes when using a deprecated ``POINTER(str)`` type in
2+
``argtypes``. Instead of aborting, ctypes now raises a proper Python
3+
exception when the pointer target type is unresolved.

Modules/_ctypes/_ctypes.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1419,7 +1419,13 @@ PyCPointerType_from_param_impl(PyObject *type, PyTypeObject *cls,
14191419
/* If we expect POINTER(<type>), but receive a <type> instance, accept
14201420
it by calling byref(<type>).
14211421
*/
1422-
assert(typeinfo->proto);
1422+
if (typeinfo->proto == NULL) {
1423+
PyErr_SetString(
1424+
PyExc_TypeError,
1425+
"cannot convert argument: POINTER _type_ type is not set"
1426+
);
1427+
return NULL;
1428+
}
14231429
switch (PyObject_IsInstance(value, typeinfo->proto)) {
14241430
case 1:
14251431
Py_INCREF(value); /* _byref steals a refcount */

0 commit comments

Comments
 (0)