gh-49960: Allow ctypes callbacks to return struct/union types - #157974
Open
freakboy3742 wants to merge 6 commits into
Open
freakboy3742 wants to merge 6 commits into
freakboy3742 wants to merge 6 commits into
Conversation
Documentation build overview
|
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
ctypescurrently prevents the definition of a callback function that returns a struct or union type.Unfortunately, it's extremely common for C code to define a callback that returns a structure (e.g. a Point).
Rubicon-ObjC has been carrying a monkypatch for ctypes since 2017 (originally authored by @dgelessus) because there are a small number of macOS Cocoa APIs that return a struct. This PR is a formalisation of that monkey patch, in the hope that we can eventually deprecate the patch.
Based on the historical discussion on gh-49960, struct/union returns were prohibited because of the potential memory implications - a returned struct is passed by value, but if the structure contains a pointer (e.g., a string), the pointer will be copied, but the memory being referenced won't be, which could lead to unexpected results.
The patch doesn't fix that potential memory leak issue - it essentially can't in the general case. Instead, it treats the problem as a user-side issue, handled with documentation. This was the approach suggested by two of the participants on gh-49960.
The patch here is slightly different to the one used in the Rubicon monkeypatch; in Rubicon, we have to patch both
getfuncandsetfuncbecause of the residual ctypes handling. By patching the problem in CPython itself, we're able to usesetfunc=Noneas a flag for "non-primitive return type" and use a memory copy.Fixes #49960.