Two equivalent styles — use whichever reads better:
// Python-style: set argtypes/restype on the bound symbol
const abs = libc.abs;
abs.argtypes = [c_int32];
abs.restype = c_int32;
abs(-42); // 42
// One-shot: declare signature at lookup
const abs2 = libc.func("abs", c_int32, [c_int32]);
abs2(-42); // 42
For Windows __stdcall APIs use WinDLL instead of CDLL. For COM-style
auto-HRESULT-checking use OleDLL.
How a call reaches C depends on its signature; the JavaScript API is the same:
call_fixed.h), preserving System V AL
and Win64 dual GP/XMM register rules for floating-point arguments.c_char_p signatures up to 32 arguments marshal
each argument straight into its precomputed register or stack offset inside
DirectAotFrame (CallSignature::direct) and invoke the static AOT assembly
trampoline (ctypes_aot_call) without intermediate slot arrays. On Apple
ARM64 fixed stack arguments are packed by size and alignment, while anonymous
variadic arguments are placed in 8-byte aligned stack slots, as that ABI
requires.long double, large stack frames
and the general path use ExecuteCall over the same AOT CallSignature and
ctypes_aot_call trampoline. The CallSignature of the declared signature is
prepared when the function is bound (unless covered by a fixed invoker); those
of calls with extra (variadic or inferred) arguments are kept in a small
per-function cache.callAsync() uses the fixed invoker of its signature or the AOT trampoline.CDLL.func() and CFUNCTYPE callers return the native function itself when
the arguments need no JavaScript conversion (numbers, booleans, BigInt, and
strings for c_char_p); calls with objects, an errcheck or other
signatures go through the JavaScript converters.
CDLL(name, mode?) or CDLL(name, { mode?, use_errno?, use_last_error? }) — C calling convention; mode is the dlopen flag (RTLD_GLOBAL, RTLD_LOCAL, DEFAULT_MODE)WinDLL(name, ...) — Windows __stdcallOleDLL(name, ...) — like WinDLL, auto-raises on negative HRESULTfind_library(name) — name resolution as in CPython 3.14: on Windows it searches PATH and returns the full path found, or null (also for "c", "m", "ssl", "crypt")util.find_library(name) / util.dllist() — CPython's ctypes.util; dllist() (CPython 3.14) returns the paths of the shared libraries loaded in the process (glibc lists the main program as ""), and is undefined on a POSIX system without dl_iterate_phdrcdll.<libname>, windll.<libname> — lazy namespaces; cdll.LoadLibrary(name), new LibraryLoader(CDLL)lib.__getitem__(name) — Python's lib[name]; on Windows an integer (Number, BigInt or boolean, masked to 16 bits) looks the export up by ordinal, as lib[1] in Python (in JS, lib[1] is the name "1"). A missing ordinal throws AttributeError function ordinal N not found; other values TypeError function name must be string, bytes object or integer. Functions read from a library have fn.__name__ (not those looked up by ordinal)restype return c_int; without argtypes the arguments are converted from their JS values (as Python)Calling a function with fewer arguments than its argtypes raises
TypeError this function takes at least 3 arguments (1 given), as CPython
does for CDLL functions (also for WinDLL / OleDLL functions and COM
methods, where CPython requires the exact count).
As in CPython, a function takes at most 1024 arguments: more argtypes
raise ArgumentError _argtypes_ has too many arguments (1025), maximum is 1024
when the prototype is created or argtypes is assigned, and a call with more
arguments ArgumentError too many arguments (1025), maximum is 1024
(callAsync() and callOn() reject with it). A COM method's this counts:
its prototype takes at most 1023 argtypes.
Without argtypes, and for variadic arguments beyond them, JS values are
converted as CPython converts Python values. An integer Number or BigInt that
fits a C long or unsigned long is passed as a C int (on LP64 a value
beyond 32 bits keeps its low 32 bits, as in CPython); a larger one raises
ArgumentError OverflowError: int too long to convert. A fractional number,
NaN or Infinity raises ArgumentError
TypeError: Don't know how to convert parameter N. Pass new c_double(x),
new c_int64(x), … for doubles and wide integers:
printf("%f %lld", new c_double(2.5), new c_int64(1n << 40n)). As in CPython, a JS
string is passed as a wchar_t * string (a Python str: UTF-16 on Windows,
UTF-32 on Linux and macOS), and a char * string needs bytes: a
NUL-terminated Buffer (Buffer.from("text\0")), a c_char_p instance
(new c_char_p("text")) or create_string_buffer("text"). For example
printf("%s\n", new c_char_p("text")); printf("%s\n", "text") prints only
t. A JS string containing a NUL character raises ArgumentError
argument N: ValueError: embedded null character. Declare argtypes
(c_char_p, c_wchar_p) to pass JS strings to
declared parameters. A Structure or Union instance is passed by value, as
in CPython (a copy of its bytes with its exact layout, also as a variadic
argument); an array is passed as a pointer, and a function pointer (a
callback, a library function, also as the _as_parameter_ of an object) as
a void *. Pass byref(s) (or pointer(s))
for the address of a structure: GetCursorPos(byref(pt)). A c_float
instance passed without argtypes retains its float width, including with
callAsync() and callOn(). Beyond a non-empty declared prefix,
node-ctypes instead applies C's default promotions (float to double,
small integers to int). Always declare the fixed prefix of a variadic function.
As in CPython, the arguments beyond a non-empty argtypes are variadic
arguments on Linux and macOS (ffi_prep_cif_var), and ordinary fixed
arguments on Windows (ffi_prep_cif: the Windows build of CPython does not use
ffi_prep_cif_var). On Windows x64 the two conventions put every argument in
the same registers. On Windows ARM64 a non-variadic function whose argtypes
omit trailing parameters receives its float, double and floating-point
structure arguments, while a variadic function such as printf does not
receive floating-point arguments beyond argtypes (CPython has the same
limitation there). The mirror case holds on macOS ARM64, where variadic
arguments go on the stack: there a non-variadic function whose argtypes omit
trailing parameters does not receive them correctly (as in CPython): declare
every fixed parameter.
restype and argtypes of a function returned by lib.func(name, restype, argtypes) are read-only: assigning them throws TypeError. Use the library
attribute (lib.name.restype = ...) or a CFUNCTYPE prototype to change a
signature.
An untyped object such as {} is rejected with TypeError when assigning
fn.argtypes or fn.restype, even before the first call, with CPython's
messages (item 1 in _argtypes_ has no from_param method,
_argtypes_ must be a sequence of types,
restype must be a type, a callable, or None). The previous declaration and
errcheck remain usable. CType numbers are still accepted (Node API).
fn.argtypes reads [] while unset (CPython: None). errcheck takes a
function or null (otherwise TypeError
the errcheck attribute must be callable). CFUNCTYPE also rejects such an
object when creating the prototype. This check does not look up the symbol
or move native ABI validation out of binding.
A declared CFUNCTYPE / WINFUNCTYPE parameter takes an instance of a
prototype: a callback, Prototype(address) or cast(fn, Prototype). Other
values, including null, integers, data instances and library functions
(lib.name), raise ArgumentError
expected CFunctionType instance instead of _FuncPtr, as in CPython.
An incomplete POINTER("Name") type
(Pointers and memory) can be declared
in argtypes before set_type(): it is resolved at each call. Until then it
takes null (NULL), and other values raise ArgumentError
expected LP_Name instance instead of c_int32.
A declared c_char_p parameter given a Buffer that does not end with a NUL
byte receives a NUL-terminated copy (Python bytes are NUL-terminated); an
empty Buffer is a valid non-NULL pointer for c_char_p and c_void_p.
As in CPython, a library is unloaded only when you ask for it: with close(),
or at the end of a using block. Garbage collection never unloads it, so
bound functions, in_dll() views and raw addresses obtained with symbol()
stay valid when the CDLL object is no longer referenced. Unused libraries
stay loaded until the process exits, as in Python.
After close(), loaded is false and its bound functions and symbol lookups
throw; close() itself throws while a call to one of them is in progress
(from a callback, or a pending callAsync()). Repeated close() calls are
harmless. Existing in_dll() views, and the Buffers, typed arrays and typed
pointer copies derived from them, keep the module loaded even after close():
the native handle is released when the last of them is collected. Raw
symbol() addresses carry no such ownership and are invalid once the module
is unloaded. Actual physical unloading depends on the OS loader: for example,
musl keeps shared libraries resident until process exit even after
dlclose().
CDLL(name, { handle }) wraps an existing module handle without taking
ownership: its close() does not unload the module. As in CPython, a handle of
0 / 0n is accepted (glibc RTLD_DEFAULT); only null or undefined mean
"load by name". A negative Number or BigInt is masked to the pointer width
(handle: -1 is glibc's RTLD_NEXT), and _handle keeps the value given,
with its sign (-1n, as CPython's _handle == -1). A value outside the
pointer range throws RangeError
could not convert the _handle attribute to a pointer, a non-integer Number
RangeError Library handle must be a valid safe integer. _name is the
name given to the constructor (null for CDLL(null)), and _handle does
not change after close(). A library name containing a NUL character throws
RangeError (embedded null character on Windows, embedded null byte
elsewhere; CPython ValueError).
CDLL(null) opens the program itself on Linux and macOS (dlopen(NULL)). On
Windows it throws TypeError without a handle, as CPython's
LoadLibrary(None) does: name the DLL instead (new CDLL("msvcrt.dll")).
On Windows CDLL("") throws Error [WinError 87] <system text>
(winerror 87), as in CPython, and a library that cannot be loaded throws
CPython's message
Could not find module 'x.dll' (or one of its dependencies). Try using the full path with constructor syntax.
with errno 2.
_as_parameter_ and from_param// Instance protocol: auto-unwrap on call
class Handle {
constructor(h) {
this._as_parameter_ = h;
}
}
user32.CloseHandle(new Handle(hwnd));
// Class protocol: custom conversion in argtypes
class StrLen extends c_int32 {
static from_param(s) {
return typeof s === "string" ? s.length : s;
}
}
const abs = libc.func("abs", c_int32, [StrLen]);
abs("hello"); // 5
As in Python, from_param receives the argument as passed (also with
CFUNCTYPE prototypes), its result is converted as the declared type, and
an error it throws becomes ArgumentError ("argument 1: RangeError: ...").
For POINTER(T), array and c_void_p parameters the result is passed
without the type check of the argument itself, as CPython does: an integer
is the address (ArgumentError OverflowError: int too long to convert
when it does not fit a pointer), null is NULL, a JS string a wchar_t *
(a UTF-8 char * for POINTER(c_char), as when the string is passed
directly), and an instance, byref(), a Buffer or an
_as_parameter_ object its address or value; anything else raises
ArgumentError argument N: TypeError: Don't know how to convert parameter N
(see Python ctypes parity for the remaining
difference).
As in CPython, any object with a from_param method is a valid argtypes
item, not only a ctypes type: an adapter instance such as
{ from_param: (v) => v } works. As node-ctypes has no C type for it, its
result is passed as a pointer-sized parameter (an integer, null, an
instance, byref(), a Buffer, …); a float result raises ArgumentError
Don't know how to convert parameter N, where CPython passes a double.
For a function-pointer parameter, _as_parameter_ may take up to 1000 steps
to resolve to a callback. A chain that does not resolve raises ArgumentError
(a rejected Promise for an asynchronous call), rather than blocking the event loop.
Non-pointer scalar CData arguments are read from their backing bytes, not an
overridden public .value getter. Each value is snapshotted before converting
the next argument, even without argtypes. A scalar from_param converter may
return a CData instance of another class when its native scalar kind matches
the declared type.
When a Structure or Union class is declared by value, its default
conversion accepts instances of that class or its subclasses. Another aggregate
with the same layout is not enough: it must supply an _as_parameter_ that
resolves to an accepted value, or the call raises ArgumentError before
converting the next argument. A custom from_param can explicitly return a
different aggregate with the correct C ABI. JavaScript field objects and byte
views are still accepted; functional struct() / union() definitions do
not impose a class check.
For a declared structure or union passed by value, the snapshot boundary is
sizeof(c_void_p), as in CPython. Above that size, a later from_param can
change the original but not the bytes the C function receives. At or below
that size, the C function can see the later change. Only the aggregate itself
is copied: pointer fields still address the same memory. Passing a pointer or
an array by address does not take this snapshot.
Objects passed through argument adapters and the objects produced by their
conversions stay alive while later arguments are converted and until the
result and errcheck have been processed. With callAsync(), those temporary
owners stay alive until its Promise settles. The native worker also retains
memory passed by value or as an integer address, including values materialized
by getters.
_as_parameter_ chains are resolved recursively, including results of
from_param, with intermediate owners retained. As in CPython, an adapter may
be visited again when a stateful getter eventually returns a usable value;
object identity alone is not rejected as a cycle, and there is no fixed
128-step limit. Non-terminating recursion raises an argument conversion error.
The available recursion depth and stack-error wording follow the JavaScript
runtime, rather than CPython's runtime-specific recursion guard.
This only covers the call: if C stores a pointer for later use, or returns a
pointer into an argument's memory, keep the source object referenced for as
long as that pointer is used. Callbacks still require explicit .release().