Skip to content

Commit fd17c9a

Browse files
committed
gh-125788: Improve ctypes error message for mismatched callback prototypes
CFUNCTYPE and WINFUNCTYPE prototypes are distinct classes that share one type name, so a mismatch was reported as "expected CFunctionType instance instead of CFunctionType". Include both signatures in the TypeError. Co-authored-by: Kağan Arıbaş <aribaskagan@gmail.com>
1 parent ca0cc50 commit fd17c9a

3 files changed

Lines changed: 118 additions & 2 deletions

File tree

‎Lib/test/test_ctypes/test_callbacks.py‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
from _ctypes import CTYPES_MAX_ARGCOUNT
99
from ctypes import (CDLL, cdll, Structure, Union, CFUNCTYPE,
1010
ArgumentError, POINTER, sizeof,
11-
c_byte, c_ubyte, c_char, c_char_p,
12-
c_short, c_ushort, c_int, c_uint,
11+
c_byte, c_ubyte, c_char, c_char_p, c_void_p,
12+
c_short, c_ushort, c_int, c_uint, c_size_t,
1313
c_long, c_longlong, c_ulonglong, c_ulong,
1414
c_float, c_double, c_longdouble, py_object)
1515
from ctypes.util import find_library, struct, wrap_dll_function
@@ -197,6 +197,81 @@ def cmp_func(a, b):
197197
libc.qsort(array, len(array), sizeof(c_int), cmp_func)
198198
self.assertEqual(array[:], [1, 5, 7, 33, 99])
199199

200+
def test_mismatched_callback_prototype(self):
201+
# gh-125788: CFUNCTYPE and WINFUNCTYPE prototypes are distinct
202+
# classes that share one type name, so a mismatch used to raise
203+
# "expected CFunctionType instance instead of CFunctionType".
204+
# Reproducer from the issue: qsort's comparator prototype does
205+
# not match the callback that is passed. Where c_int is an alias
206+
# of c_long, those two prototypes are the same object; a shorter
207+
# argument list keeps them distinct.
208+
def signature(proto):
209+
return (f"(restype={proto._restype_!r}, "
210+
f"argtypes={proto._argtypes_!r})")
211+
212+
def message(expected, actual):
213+
return (
214+
f"expected {expected.__name__} instance with signature "
215+
f"{signature(expected)} instead of "
216+
f"{actual.__name__} instance with signature "
217+
f"{signature(actual)}"
218+
)
219+
220+
def cmp(*args):
221+
return 0
222+
223+
cmp_int = CFUNCTYPE(c_int, c_void_p, c_void_p)
224+
cmp_long = CFUNCTYPE(c_long, c_void_p, c_void_p)
225+
if cmp_int is cmp_long:
226+
cmp_long = CFUNCTYPE(c_long, c_void_p)
227+
228+
long_cb = cmp_long(cmp)
229+
mismatch = message(cmp_int, cmp_long)
230+
with self.assertRaises(TypeError) as cm:
231+
cmp_int.from_param(long_cb)
232+
self.assertEqual(str(cm.exception), mismatch)
233+
234+
# A matching callback is still accepted unchanged.
235+
good = cmp_int(cmp)
236+
self.assertIs(cmp_int.from_param(good), good)
237+
238+
# Values that are not callbacks keep the generic message.
239+
with self.assertRaises(TypeError) as cm:
240+
cmp_int.from_param(object())
241+
self.assertEqual(str(cm.exception),
242+
"expected CFunctionType instance instead of object")
243+
244+
# Argument types differ, so each side of the message is checked
245+
# independently of the result type.
246+
cmp_chars = CFUNCTYPE(c_int, c_char_p)
247+
with self.assertRaises(TypeError) as cm:
248+
cmp_int.from_param(cmp_chars(cmp))
249+
self.assertEqual(str(cm.exception), message(cmp_int, cmp_chars))
250+
251+
if hasattr(ctypes, 'WINFUNCTYPE'):
252+
win_int = ctypes.WINFUNCTYPE(c_int, c_void_p, c_void_p)
253+
win_long = ctypes.WINFUNCTYPE(c_long, c_void_p, c_void_p)
254+
if win_int is win_long:
255+
win_long = ctypes.WINFUNCTYPE(c_long, c_void_p)
256+
with self.assertRaises(TypeError) as cm:
257+
win_int.from_param(win_long(cmp))
258+
self.assertEqual(str(cm.exception), message(win_int, win_long))
259+
260+
libc_path = find_library("c")
261+
if not libc_path:
262+
return
263+
libc = CDLL(libc_path)
264+
try:
265+
qsort = libc.qsort
266+
except (AttributeError, OSError, ValueError):
267+
return
268+
qsort.restype = None
269+
qsort.argtypes = [c_void_p, c_size_t, c_size_t, cmp_int]
270+
with self.assertRaises(ArgumentError) as cm:
271+
qsort(None, 0, sizeof(c_int), long_cb)
272+
self.assertEqual(str(cm.exception),
273+
f"argument 4: TypeError: {mismatch}")
274+
200275
@unittest.skipUnless(hasattr(ctypes, 'WINFUNCTYPE'),
201276
'ctypes.WINFUNCTYPE is required')
202277
def test_issue_8959_b(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:mod:`ctypes` now includes the expected and actual callback signatures in
2+
the :exc:`TypeError` raised when a :func:`~ctypes.CFUNCTYPE` or
3+
:func:`~ctypes.WINFUNCTYPE` argument does not match the prototype.

‎Modules/_ctypes/_ctypes.c‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,44 @@ CDataType_from_param_impl(PyObject *type, PyTypeObject *cls, PyObject *value)
11231123
_Py_LeaveRecursiveCall();
11241124
return value;
11251125
}
1126+
/*
1127+
CFUNCTYPE and WINFUNCTYPE prototypes are distinct classes that
1128+
share one type name (CFunctionType or WinFunctionType). Include
1129+
both signatures so a mismatch can be told apart. Other mismatches
1130+
keep the generic message. (gh-125788)
1131+
*/
1132+
if (PyCFuncPtrTypeObject_Check(st, type) &&
1133+
PyCFuncPtrObject_Check(st, value)) {
1134+
StgInfo *expected_info;
1135+
StgInfo *actual_info;
1136+
1137+
if (PyStgInfo_FromType(st, type, &expected_info) < 0) {
1138+
return NULL;
1139+
}
1140+
if (PyStgInfo_FromType(st, (PyObject *)Py_TYPE(value),
1141+
&actual_info) < 0) {
1142+
return NULL;
1143+
}
1144+
if (expected_info != NULL && actual_info != NULL &&
1145+
expected_info->argtypes != NULL &&
1146+
actual_info->argtypes != NULL) {
1147+
PyObject *expected_restype = expected_info->restype ?
1148+
expected_info->restype : Py_None;
1149+
PyObject *actual_restype = actual_info->restype ?
1150+
actual_info->restype : Py_None;
1151+
PyErr_Format(PyExc_TypeError,
1152+
"expected %s instance with signature "
1153+
"(restype=%R, argtypes=%R) instead of %s instance "
1154+
"with signature (restype=%R, argtypes=%R)",
1155+
((PyTypeObject *)type)->tp_name,
1156+
expected_restype,
1157+
expected_info->argtypes,
1158+
Py_TYPE(value)->tp_name,
1159+
actual_restype,
1160+
actual_info->argtypes);
1161+
return NULL;
1162+
}
1163+
}
11261164
PyErr_Format(PyExc_TypeError,
11271165
"expected %s instance instead of %s",
11281166
((PyTypeObject *)type)->tp_name,

0 commit comments

Comments
 (0)