Skip to content

Commit b97f5e7

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

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

1911-
*arguments* is a tuple containing the parameters originally passed to
1912-
the function call, this allows specializing the behavior on the
1911+
*arguments* is a tuple containing the parameters passed to the
1912+
function call, including any output parameters that :mod:`!ctypes`
1913+
created for the call; this allows specializing the behavior on the
19131914
arguments used.
19141915

1915-
The object that this function returns will be returned from the
1916-
foreign function call, but it can also check the result value
1917-
and raise an exception if the foreign function call failed.
1916+
If the callable returns the *arguments* tuple it received, unchanged,
1917+
:mod:`!ctypes` continues its normal processing of the result, which
1918+
includes returning output parameters (see
1919+
:ref:`ctypes-function-prototypes`). Any other object returned by the
1920+
callable is returned from the foreign function call instead. The
1921+
callable can also check the result value and raise an exception if the
1922+
foreign function call failed.
1923+
1924+
For example, this callable raises an exception when the foreign function
1925+
signals failure with a negative return value, and otherwise leaves the
1926+
result to :mod:`!ctypes`::
1927+
1928+
def errcheck(result, func, arguments):
1929+
if result < 0:
1930+
raise RuntimeError(f"call failed with error {result}")
1931+
return arguments
1932+
1933+
This one instead replaces the result, converting a C ``int`` used as a
1934+
boolean into a :class:`bool`::
1935+
1936+
def errcheck(result, func, arguments):
1937+
return result != 0
19181938

19191939

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

0 commit comments

Comments
 (0)