errno and GetLastErrorget_last_error() / get_errno() read a private thread-local slot,
exactly like Python's ctypes.get_last_error() / ctypes.get_errno().
The slot is updated only by FFI calls through libraries or prototypes
opened with use_last_error or use_errno; unflagged calls leave it
unchanged. As in Python those calls swap it with the system value: the
function sees the value set with set_errno() / set_last_error(), the value
it leaves becomes the private one, and the system value is restored after the
call. lib.get_last_error() / lib.get_errno() return the same thread value
as the top-level functions, not a per-library copy, and throw Error
Library was not opened with use_last_error: true (use_errno: true) when
the library was opened without that flag (a Node extension kept from 2.x). A
CFUNCTYPE /
WINFUNCTYPE callback with use_errno / use_last_error swaps the same way
around the JavaScript function: inside it get_errno() / get_last_error()
return the value the C caller left, and the value set with set_errno() /
set_last_error() is what the C caller sees when the callback returns.
const user32 = new WinDLL("user32.dll", { use_last_error: true });
const FindWindow = user32.func("FindWindowW", c_void_p, [c_wchar_p, c_wchar_p]);
FindWindow("NoSuchClass", null);
get_last_error(); // Python: ctypes.get_last_error()
As in CPython, the private last error is a signed C int
(get_last_error() returns -2147024891 for 0x80070005), and
set_errno(v) / set_last_error(v) take exactly one integer (Number, BigInt
or boolean) in the C int range and return the previous value. A value out
of range is a RangeError (Python int too large to convert to C long on
Windows, signed integer is greater than maximum / signed integer is less than minimum elsewhere), a non-integer a TypeError
('float' object cannot be interpreted as an integer), and another number of
arguments a TypeError (function takes exactly 1 argument (N given)). Pass
an HRESULT-style code signed: set_last_error(0x80070005 | 0).
The snapshot is captured in native code immediately after the native call, whether direct or through the AOT trampoline, before any other JS can clobber it.
GetLastError() / SetLastError(v) read and write the system value of the
calling thread (kernel32), as ctypes.GetLastError does. They exist on
Windows only, as in CPython. GetLastError() returns the value left by the
previous foreign call even when JavaScript code or the garbage collector ran
in between; other system calls made by your own code in between (through
node-ctypes or Node.js) can still change it, so prefer use_last_error and
get_last_error().
GetLastError() is signed, as CPython's (0xdeadbeef reads as
-559038737). WinError() and FormatError() without a code use
GetLastError(), also for HRESULT-style codes: after
SetLastError(0x80070005), WinError().winerror is -2147024891 and its
errno is 13. An explicit code is read as a C long: pass it signed
(WinError(0x80070005 | 0)). As in CPython, FormatError(0) also formats
GetLastError(), WinError(0) keeps winerror 0 with that text,
FormatError(null) is a TypeError, and WinError(n).filename is null.
On Windows the addon uses the shared Universal CRT (ucrtbase.dll), as
CPython does: use_errno and get_errno() see errno set by ucrtbase.dll
and by DLLs built with /MD. A DLL with a static CRT (/MT) or one using
msvcrt.dll keeps its own errno, also in CPython.
errcheck)Set fn.errcheck = (result, func, args) => ... to check or replace a result,
or set it to null to clear it; another value throws TypeError
the errcheck attribute must be callable. As in CPython, a hook that returns
its own args array returns the result of the call (for paramflags
functions, the output parameters: see below). For lib.func(), library
attributes and
CFUNCTYPE / WINFUNCTYPE callers, func is the public callable and args
contains the original, unconverted arguments. Result conversion and any
OleDLL HRESULT check run before the hook.
Each invocation captures its hook before argument adapters or getters run.
Replacing or clearing it affects later invocations, including reentrant calls,
not the call already in progress or a pending callAsync() job.
Hooks do not prevent otherwise unreachable functions and libraries from being
garbage-collected, even when they reference the function itself. Active calls
and workers retain their captured hook through result checking; close() is
still rejected while that checking runs.
The low-level native handle's setErrcheck() API instead passes the native
handle as func, invoked with .call(), not a directly callable function.
paramflags)When at least one out param is declared, the call returns only the
out-params (single value, or array if >1) — the restype is
discarded. To also inspect it (e.g. a thread ID or success flag), attach an
errcheck:
const { DWORD, HWND, LPDWORD } = wintypes;
const proto = WINFUNCTYPE(DWORD, HWND, LPDWORD);
const fn = proto.bind(user32, "GetWindowThreadProcessId", [
{ dir: "in", name: "hWnd" },
{ dir: "out", name: "pid" },
]);
const pid = fn(hwnd); // positional; thread ID is discarded
const p2 = fn({ hWnd: hwnd }); // or named-args
fn.errcheck = (threadId, func, args) => {
if (!threadId) throw new Error("call failed");
return args; // continue returning the PID from the output instance
};
const p3 = await fn.callAsync(hwnd);
fn.errcheck = (threadId, func, args) => {
if (!threadId) throw new Error("call failed");
return { threadId, processId: args[1].value };
};
const ids = fn(hwnd); // inspect both the return value and the output parameter
As in Python, the value returned by errcheck is the result of the call,
unless it is args itself: then the out-params are returned. Here args
is the expanded argument list, with out-params as instances. When the hook
returns args, output processing uses the original instances: changing
args[i].value affects the result, but replacing args[i] does not.
These bindings have their own hook, independent of any cached lib.func()
binding, and support callAsync() with the same output processing and
per-call hook snapshot. Adapter temporaries stay alive through that processing,
also when the hook throws.
OUT conversion invokes the output instance's __ctypes_from_outparam__().
By default a builtin scalar yields its value, while a scalar subclass yields
the instance. Override the method for custom output conversion.
An OUT parameter declared with a default ([2, "name", value]) passes that
default to C instead of allocating a new instance, and returns it through
__ctypes_from_outparam__(), as CPython: a c_int32 default returns its
value after the call, a pointer default the same pointer object. A default
that is not C data (null, byref(x)) raises AttributeError
'NoneType' object has no attribute '__ctypes_from_outparam__' after the
arguments are converted (an ArgumentError of an argument comes first, as in
CPython); the call itself, which could only write through NULL, is not made.
OUT applies to POINTER(T) and array argtypes (the pointee or array is
allocated); on c_void_p / c_char_p / c_wchar_p (and subclasses) it needs
a default: without one the call raises TypeError
c_void_p 'out' parameter must be passed as default value. Any other argtype
is rejected when the function is created (TypeError
'out' parameter 1 must be a pointer type, not c_int32). Errors are raised in
parameter order, as CPython's _build_callargs.
Use { dir: "inout", name: "value" }, or tuple flag 3, to pass an existing
instance and return that exact instance after C modifies it. INOUT works with
any argtype; a value the argtype rejects raises its usual error (e.g.
argument 1: TypeError: expected LP_c_int64 instance instead of int). INOUT
does not call __ctypes_from_outparam__; positional, named and default
arguments use the same rule. Mixed outputs preserve parameter order. If errcheck returns
anything other than the original args, neither OUT nor INOUT unpacking runs.
Flags are validated as CPython's _validate_paramflags: 0, 1 (in), 2
(out), 3 (inout) and 5 (in | lcid) are accepted; 4, 6 and 7 throw
TypeError paramflag value 4 not supported when the function is created.
An lcid parameter takes its default (or 0) without consuming an
argument. A malformed item throws TypeError
paramflags must be a sequence of (int [,string [,value]]) tuples, and a
length different from argtypes RangeError
paramflags must have the same length as argtypes.
get_errno() / set_errno(v)get_last_error() / set_last_error(v) — the private slot (all platforms; Python: Windows only)GetLastError() / SetLastError(v) — the system value (Windows only)FormatError(code?) / WinError(code?, descr?) — system message text and an OSError-shaped error; without a code they use GetLastError() (Windows only)ArgumentError — raised for arguments that do not match argtypes ("argument N: TypeError: ...")lib.get_last_error() / lib.get_errno() — the same thread value as the top-level functions; they throw unless the library was opened with use_last_error / use_errno (Node extension)A negative HRESULT (an OleDLL function, or an explicit HRESULT restype)
raises an error shaped like CPython's OSError: the message is
[WinError <signed code>] <system text>, strerror is the system text without
trailing dots (or Windows Error 0x<code> when the system has none), winerror
and hresult are the signed code, errno is the matching C errno, and
filename is null. error.function names the loader and function that
failed.
On Windows builds compiled with MSVC (_WIN32 and _MSC_VER, the toolchain
of the published win32-x64 and win32-arm64 prebuilds, which cmake-js
builds with the Visual Studio generator) a fault inside a foreign call (an
access violation or another structured exception) does not end the process:
as CPython, the call throws
an Error (or rejects the promise of callAsync() / callOn()) with the
message exception: access violation reading 0x0000000000000010
(writing for a write), exception: <description> for other exception
codes, or [WinError N] <system text> with winerror and errno. The
memory the function was using may be left inconsistent. Windows builds from
source with MinGW/GCC have no structured exception guard, and on Linux and
macOS a fault still terminates the process, as in CPython. As CPython, which
implements them as foreign calls, string_at(), wstring_at(), memmove()
and memset() are guarded too: a bad address (also behind a Buffer or an
instance created by from_address()) throws the same Error
(string_at(16): exception: access violation reading 0x0000000000000010,
memset(16, 0, 4): ... writing ...; a large string_at(16, n) fails the
same way before allocating n bytes). Reading or writing a field of an
instance created by from_address() on a bad address, or readValue() /
writeValue(), is not guarded and faults in both.