Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Lib/test/test_ctypes/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,17 @@ def func():
f"of ctypes callback function {func!r}")
self.assertIsNone(cm.unraisable.object)

def test_callback_return_subclass(self):
class MyInt(ctypes.c_int):
pass

@ctypes.CFUNCTYPE(MyInt, MyInt)
def identity(x):
return x

result = identity(MyInt(42))
assert isinstance(result, MyInt)
assert result.value == 42

if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix ctypes callback return handling for subclassed simple types.

Returning a ctypes instance (e.g. a subclass of c_int) from a CFUNCTYPE
callback no longer raises an unraisable TypeError or leaves the result
buffer uninitialized.
14 changes: 13 additions & 1 deletion Modules/_ctypes/callbacks.c
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,19 @@ static void _CallPythonObject(ctypes_state *st,
be the result. EXCEPT when restype is py_object - Python
itself knows how to manage the refcount of these objects.
*/
PyObject *keep = setfunc(mem, result, restype->size);
PyObject *value = result; /* borrowed */
PyObject *unwrapped = NULL; /* new ref if created */
if (value != NULL && PyObject_TypeCheck(value, st->PyCData_Type)) {
unwrapped = PyObject_GetAttrString(value, "value");
if (unwrapped != NULL) {
value = unwrapped;
} else {
/* fallback: clear error and keep original */
PyErr_Clear();
}
}

PyObject *keep = setfunc(mem, value, restype->size);

if (keep == NULL) {
/* Could not convert callback result. */
Expand Down
Loading