Skip to content

Commit 8b2a373

Browse files
gh-112423: Clarify how to use errcheck for ctypes function pointers (GH-159776)
1 parent d1dd070 commit 8b2a373

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
@@ -1992,13 +1992,33 @@ in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class:
19921992
same callable object to check or post process the results of several
19931993
functions.
19941994

1995-
*arguments* is a tuple containing the parameters originally passed to
1996-
the function call, this allows specializing the behavior on the
1995+
*arguments* is a tuple containing the parameters passed to the
1996+
function call, including any output parameters that :mod:`!ctypes`
1997+
created for the call; this allows specializing the behavior on the
19971998
arguments used.
19981999

1999-
The object that this function returns will be returned from the
2000-
foreign function call, but it can also check the result value
2001-
and raise an exception if the foreign function call failed.
2000+
If the callable returns the *arguments* tuple it received, unchanged,
2001+
:mod:`!ctypes` continues its normal processing of the result, which
2002+
includes returning output parameters (see
2003+
:ref:`ctypes-function-prototypes`). Any other object returned by the
2004+
callable is returned from the foreign function call instead. The
2005+
callable can also check the result value and raise an exception if the
2006+
foreign function call failed.
2007+
2008+
For example, this callable raises an exception when the foreign function
2009+
signals failure with a negative return value, and otherwise leaves the
2010+
result to :mod:`!ctypes`::
2011+
2012+
def errcheck(result, func, arguments):
2013+
if result < 0:
2014+
raise RuntimeError(f"call failed with error {result}")
2015+
return arguments
2016+
2017+
This one instead replaces the result, converting a C ``int`` used as a
2018+
boolean into a :class:`bool`::
2019+
2020+
def errcheck(result, func, arguments):
2021+
return result != 0
20022022

20032023

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

0 commit comments

Comments
 (0)