Repository navigation
gh-49960: Allow ctypes callbacks to return struct/union types #157974
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ZeroIntensity
merged 10 commits into
python:main
from
freakboy3742:ctypes-struct-return
Oct 22, 2026
+429
−59
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2da8185
gh-49960: add ctypes test helpers for struct-returning callbacks
freakboy3742 5484950
gh-49960: add failing tests for struct/union callback returns
freakboy3742 63ee2fb
gh-49960: allow struct and union restypes for ctypes callbacks
freakboy3742 d2363f1
gh-49960: copy struct/union results from ctypes callbacks
freakboy3742 94c0f60
gh-49960: document struct and union returns from ctypes callbacks
freakboy3742 5894376
Clean up test cases for consistency.
freakboy3742 d7707be
Merge remote-tracking branch 'upstream/main' into ctypes-struct-return
freakboy3742 dae031c
Merge branch 'main' into ctypes-struct-return
freakboy3742 bf97330
Address review feedback.
freakboy3742 3abcd9b
Merge branch 'main' into ctypes-struct-return
freakboy3742 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,14 +4,15 @@ | |
| import math | ||
| import sys | ||
| import unittest | ||
| import warnings | ||
| from _ctypes import CTYPES_MAX_ARGCOUNT | ||
| from ctypes import (CDLL, cdll, Structure, CFUNCTYPE, | ||
| from ctypes import (CDLL, cdll, Structure, Union, CFUNCTYPE, | ||
| ArgumentError, POINTER, sizeof, | ||
| c_byte, c_ubyte, c_char, | ||
| c_byte, c_ubyte, c_char, c_char_p, | ||
| c_short, c_ushort, c_int, c_uint, | ||
| c_long, c_longlong, c_ulonglong, c_ulong, | ||
| c_float, c_double, c_longdouble, py_object) | ||
| from ctypes.util import find_library, wrap_dll_function | ||
| from ctypes.util import find_library, struct, wrap_dll_function | ||
| from test import support | ||
| from test.support import import_helper | ||
| _ctypes_test = import_helper.import_module("_ctypes_test") | ||
|
|
@@ -293,6 +294,222 @@ def callback(check, s): | |
| self.assertEqual(s.second, check.second) | ||
| self.assertEqual(s.third, check.third) | ||
|
|
||
| # gh-49960: callbacks may return structures and unions by value. | ||
|
|
||
| def test_callback_return_small_struct(self): | ||
| @struct | ||
| class SmallRet: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = SmallRet | ||
|
|
||
| result = func(CALLBACK(lambda: SmallRet(17, 42))) | ||
| self.assertEqual((result.a, result.b), (17, 42)) | ||
|
|
||
| def test_callback_return_struct_reaches_c(self): | ||
| # The C helper sums the fields itself, proving the bytes actually | ||
| # reached the C caller rather than only round-tripping in Python. | ||
| @struct | ||
| class SmallRet: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct_sum | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = c_long | ||
|
|
||
| self.assertEqual(func(CALLBACK(lambda: SmallRet(300, 45))), 345) | ||
|
|
||
| def test_callback_return_large_struct(self): | ||
| # Mirrors `Test` in Modules/_ctypes/_ctypes_test.c: >8 bytes, so it | ||
| # is returned via a hidden pointer rather than in registers. | ||
| @struct | ||
| class X: | ||
| first: c_ulong | ||
| second: c_ulong | ||
| third: c_ulong | ||
|
|
||
| CALLBACK = CFUNCTYPE(X) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_large_struct | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = X | ||
|
|
||
| result = func(CALLBACK(lambda: X(0xdeadbeef, 0xcafebabe, 0x0bad1dea))) | ||
| self.assertEqual(result.first, 0xdeadbeef) | ||
| self.assertEqual(result.second, 0xcafebabe) | ||
| self.assertEqual(result.third, 0x0bad1dea) | ||
|
|
||
| def test_callback_return_float_struct(self): | ||
| # All-float struct: SSE class on x86-64, HFA on AArch64. | ||
| @struct | ||
| class FloatRet: | ||
| x: c_double | ||
| y: c_double | ||
|
|
||
| CALLBACK = CFUNCTYPE(FloatRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_float_struct | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = FloatRet | ||
|
|
||
| result = func(CALLBACK(lambda: FloatRet(1.5, -2.25))) | ||
| self.assertEqual((result.x, result.y), (1.5, -2.25)) | ||
|
|
||
| def test_callback_return_union(self): | ||
| class UnionRet(Union): | ||
| _fields_ = [("i", c_int), ("f", c_float)] | ||
|
|
||
| CALLBACK = CFUNCTYPE(UnionRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_union | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = UnionRet | ||
|
|
||
| result = func(CALLBACK(lambda: UnionRet(i=0x41424344))) | ||
| self.assertEqual(result.i, 0x41424344) | ||
|
|
||
| def test_callback_return_struct_repeatedly(self): | ||
| # Guards against per-call leaks and against regressing into the | ||
| # "memory leak in callback function" RuntimeWarning path. | ||
| @struct | ||
| class SmallRet: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct_sum | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = c_long | ||
|
|
||
| cb = CALLBACK(lambda: SmallRet(1, 2)) | ||
| # A RuntimeWarning raised inside the callback is reported as an | ||
| # unraisable exception rather than propagated, so check for those. | ||
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("error", RuntimeWarning) | ||
|
Comment on lines
+396
to
+397
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need to catch unraisable exceptions that result from this. |
||
| with support.catch_unraisable_exception() as cm: | ||
| for _ in range(100): | ||
| self.assertEqual(func(cb), 3) | ||
| self.assertIsNone(cm.unraisable) | ||
|
|
||
| def test_callback_return_struct_subclass(self): | ||
| # isinstance semantics: a subclass instance is acceptable. | ||
| @struct | ||
| class SmallRet: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| class SubRet(SmallRet): | ||
| pass | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct_sum | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = c_long | ||
|
|
||
| self.assertEqual(func(CALLBACK(lambda: SubRet(4, 5))), 9) | ||
|
|
||
| def test_callback_return_struct_wrong_type(self): | ||
| @struct | ||
| class SmallRet: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| @struct | ||
| class Other: | ||
| q: c_int | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct_sum | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = c_long | ||
|
|
||
| for bad in (None, 42, Other(1)): | ||
| with self.subTest(bad=bad): | ||
| def cb(bad=bad): | ||
| return bad | ||
| with support.catch_unraisable_exception() as cm: | ||
| # As with other result types, the value returned to C | ||
| # after a conversion failure is undefined; don't test it. | ||
| func(CALLBACK(cb)) | ||
| self.assertIsInstance(cm.unraisable.exc_value, TypeError) | ||
| self.assertEqual( | ||
| cm.unraisable.err_msg, | ||
| f"Exception ignored while converting result " | ||
| f"of ctypes callback function {cb!r}") | ||
|
|
||
| def test_callback_return_struct_with_pointer(self): | ||
| # gh-49960 / bpo-5710 discussion: the struct is copied by value, so | ||
| # any pointer it contains must reference memory the caller keeps | ||
| # alive. Here `keepalive` does exactly that. | ||
| @struct | ||
| class WithPtr: | ||
| s: c_char_p | ||
|
|
||
| keepalive = b"hello" | ||
|
|
||
| CALLBACK = CFUNCTYPE(WithPtr) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_ptr_struct | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = WithPtr | ||
|
|
||
| result = func(CALLBACK(lambda: WithPtr(keepalive))) | ||
| self.assertEqual(result.s, b"hello") | ||
|
|
||
| def test_callback_return_struct_ignores_instancecheck(self): | ||
| # The result type is checked without running Python code, so a | ||
| # metaclass __instancecheck__ cannot cause a smaller structure to be | ||
| # accepted (which would read past the end of its buffer). | ||
| class Meta(type(Structure)): | ||
| def __instancecheck__(cls, inst): | ||
| return True | ||
|
|
||
| # Not @struct: it would rebuild the class and drop the metaclass. | ||
| class SmallRet(Structure, metaclass=Meta): | ||
| _fields_ = [("a", c_int), ("b", c_int)] | ||
|
|
||
| @struct | ||
| class Tiny: | ||
| x: c_byte | ||
|
|
||
| CALLBACK = CFUNCTYPE(SmallRet) | ||
| dll = CDLL(_ctypes_test.__file__) | ||
| func = dll._testfunc_cbk_ret_small_struct_sum | ||
| func.argtypes = (CALLBACK,) | ||
| func.restype = c_long | ||
|
|
||
| def cb(): | ||
| return Tiny(5) | ||
| with support.catch_unraisable_exception() as cm: | ||
| func(CALLBACK(cb)) | ||
| self.assertIsInstance(cm.unraisable.exc_value, TypeError) | ||
|
|
||
| def test_callback_return_struct_fields_final(self): | ||
| # Once a structure is used as a callback's result type, its layout | ||
| # is fixed: the callback's libffi signature depends on it. | ||
| @struct | ||
| class Base: | ||
| a: c_int | ||
| b: c_int | ||
|
|
||
| class Sub(Base): | ||
| pass | ||
|
|
||
| CFUNCTYPE(Sub)(lambda: Sub(1, 2)) | ||
| with self.assertRaisesRegex(AttributeError, "_fields_ is final"): | ||
| Sub._fields_ = [("c", c_double)] | ||
|
|
||
| def test_callback_too_many_args(self): | ||
| def func(*args): | ||
| return len(args) | ||
|
|
||
3 changes: 3 additions & 0 deletions
3
Misc/NEWS.d/next/Library/2026-09-18-00-00-00.gh-issue-49960.MDT3jE.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| :mod:`ctypes` callback functions can now return structures and unions by | ||
| value. Previously only "simple" types could be returned, and any other result | ||
| type raised :exc:`TypeError`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please also add something to the 3.16 whatsnew.