Skip to content

Commit 02f9a2e

Browse files
[3.15] gh-112423: Clarify how to use errcheck for ctypes function pointers (GH-159776) (GH-159783)
(cherry picked from commit 8b2a373) Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
1 parent 61b4101 commit 02f9a2e

1 file changed

Lines changed: 25 additions & 5 deletions

File tree

‎Doc/library/ctypes.rst‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1946,13 +1946,33 @@ in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class:
19461946
same callable object to check or post process the results of several
19471947
functions.
19481948

1949-
*arguments* is a tuple containing the parameters originally passed to
1950-
the function call, this allows specializing the behavior on the
1949+
*arguments* is a tuple containing the parameters passed to the
1950+
function call, including any output parameters that :mod:`!ctypes`
1951+
created for the call; this allows specializing the behavior on the
19511952
arguments used.
19521953

1953-
The object that this function returns will be returned from the
1954-
foreign function call, but it can also check the result value
1955-
and raise an exception if the foreign function call failed.
1954+
If the callable returns the *arguments* tuple it received, unchanged,
1955+
:mod:`!ctypes` continues its normal processing of the result, which
1956+
includes returning output parameters (see
1957+
:ref:`ctypes-function-prototypes`). Any other object returned by the
1958+
callable is returned from the foreign function call instead. The
1959+
callable can also check the result value and raise an exception if the
1960+
foreign function call failed.
1961+
1962+
For example, this callable raises an exception when the foreign function
1963+
signals failure with a negative return value, and otherwise leaves the
1964+
result to :mod:`!ctypes`::
1965+
1966+
def errcheck(result, func, arguments):
1967+
if result < 0:
1968+
raise RuntimeError(f"call failed with error {result}")
1969+
return arguments
1970+
1971+
This one instead replaces the result, converting a C ``int`` used as a
1972+
boolean into a :class:`bool`::
1973+
1974+
def errcheck(result, func, arguments):
1975+
return result != 0
19561976

19571977

19581978
.. audit-event:: ctypes.set_exception code foreign-functions

0 commit comments

Comments
 (0)