Skip to content

Commit 8617d76

Browse files
gh-144100: Fix crash for POINTER(str) used in ctypes argtypes
1 parent 4ef30a5 commit 8617d76

3 files changed

Lines changed: 28 additions & 1 deletion

File tree

Lib/test/test_ctypes/test_pointers.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import gc
44
import sys
55
import unittest
6+
import os
67
from ctypes import (CDLL, CFUNCTYPE, Structure,
78
POINTER, pointer, _Pointer,
89
byref, sizeof,
@@ -472,6 +473,23 @@ class C(Structure):
472473
ptr.set_type(c_int)
473474
self.assertIs(ptr._type_, c_int)
474475

476+
class TestPointerStringProto(unittest.TestCase):
477+
def test_pointer_string_proto_argtypes_error(self):
478+
479+
BadType = ctypes.POINTER("BugTrigger")
480+
481+
if os.name == "nt":
482+
libc = ctypes.WinDLL("kernel32.dll")
483+
func = libc.GetCurrentProcessId
484+
else:
485+
libc = ctypes.CDLL(None)
486+
func = libc.getpid
487+
488+
func.argtypes = (BadType,)
489+
490+
with self.assertRaises(ctypes.ArgumentError):
491+
func(ctypes.byref(ctypes.c_int(0)))
492+
475493

476494
if __name__ == '__main__':
477495
unittest.main()
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 target type is unresolved"
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)