node-ctypes - v2.17.1
    Preparing search index...

    Callbacks

    import { callback, CFUNCTYPE, c_int32, c_void_p, readValue } from "node-ctypes";

    // Python-style type: CFUNCTYPE(restype, ...argtypes)
    const CompareFn = CFUNCTYPE(c_int32, c_void_p, c_void_p);
    const cmp = new CompareFn((a, b) => readValue(a, c_int32) - readValue(b, c_int32));

    // Or the one-shot form:
    const cmp2 = callback((a, b) => readValue(a, c_int32) - readValue(b, c_int32), c_int32, [c_void_p, c_void_p]);

    // Pass the callback itself (as in Python) or its address `cmp.pointer`.
    qsort(arr, 5, 4, cmp);

    // CFUNCTYPE types also work as struct fields (read back as a callable).

    // IMPORTANT: release the trampoline when done. Unlike Python, we cannot
    // rely on GC — the callback holds a native trampoline that C code may
    // still reference.
    cmp.release();
    cmp2.release();

    If C stores the callback pointer, keep the wrapper alive until you have unregistered the callback and all calls in flight have returned. Then call release().

    CFUNCTYPE and WINFUNCTYPE weakly intern live prototypes by the complete identity and order of their argument/return types, separately for each calling convention. Repeated requests reuse the same live prototype, as in Python, without keeping abandoned types alive. Callers, callbacks and output bindings retain their prototype while they are live.

    Prototype metadata is shared. Changing its public restype / argtypes metadata does not recompile the captured native signature or alter cache keys; request a different signature to change the ABI. Each new caller prepares its argument-conversion pipeline and captures its result-check hook independently. Existing callers retain their result-check snapshot and their own errcheck. An installed from_param converter still resolves the method at call time, as before.

    Structure, union and scalar-instance arguments received by callback(), CFUNCTYPE and threadSafeCallback() are owned snapshots. For a Structure or Union class passed by value, ctypes calls the constructor with no arguments, then copies the C bytes into that same instance. The constructor can inspect its initially zeroed fields and save views of them. The handler and those views see the C values, not the constructor's field writes. This differs from a function returning a class by value, which skips the constructor. Pointer fields copy the address, not the pointed-to memory.

    An argument declared as a CFUNCTYPE prototype is received as a callable instance of that prototype (arg instanceof Proto), not as an address.

    The JavaScript result is converted as CPython's setfunc of the restype. A numeric restype takes a Number, BigInt or boolean: a ctypes instance raises TypeError ('c_int32' object cannot be interpreted as an integer, must be real number, not c_int32), which is reported as unraisable (a CallbackError process warning, or the wrapper's error handler) and returns 0 to C; a c_bool result uses the truth value of whatever is returned. A c_char_p / c_wchar_p / c_void_p result takes null, an integer address or a boolean (address 1 / 0), and a c_char_p / c_wchar_p result also a string (a c_char_p result also a Buffer); typed arrays, ctypes instances and byref() raise TypeError (for c_char_p: bytes or integer address expected instead of _ctypes.CArgObject instance).

    A c_wchar_p callback returning a JS string allocates a terminated wide string and emits RuntimeWarning: memory leak in callback function., like CPython. C may keep the result even after release() of the trampoline: the storage is retained until the Node environment exits. A Buffer returned for c_char_p has the same lifetime and warning. Narrow JS strings are a Node extension: their UTF-8 bytes are cached by value per callback, without that warning. For frequently changing results, use a caller-owned output buffer if the C API supports one.

    Signatures with a class aggregate keep incoming bytes in dedicated buffers, so a reentrant constructor cannot alter them through a previously exposed snapshot pool. Otherwise, small functional struct()/union() arguments slice an 8 KB native C++ pool directly (Uint8Array) and are exposed through cached prototype-backed views without per-call Proxy objects (including small native-endian numeric array fields up to 64 elements, while preserving full CPython write validation); scalar-instance arguments and mirror mode use the dedicated JS snapshot pool. Native-call temporaries use a separate pool that is never exposed. Slices are never reused. Detaching a pooled snapshot's ArrayBuffer only affects snapshots in that pool; later callbacks use a fresh one.

    • Retaining any slice keeps its whole 8 KB backing ArrayBuffer alive. When storing many small arguments for a long time, copy them, for example Buffer.from(value._buffer) or a new instance built from its fields.
    • value._buffer.buffer is the whole pool and can contain other callback snapshots. Use _buffer itself (or byteOffset and length), and copy before handing the underlying ArrayBuffer to untrusted code.

    Values larger than 2 KB, layouts aligned to more than 8 bytes and raw native callbacks keep a dedicated allocation.

    Both callbacks and libraries implement Symbol.dispose, so they work with the using declaration for scope-bound cleanup (also on throw):

    {
    using libc = new CDLL(process.platform === "win32" ? "msvcrt.dll" : null);
    using cmp = callback(fn, c_int32, [c_void_p, c_void_p]);
    qsort(arr, 5, 4, cmp);
    } // close() + release() run automatically

    Set NODE_CTYPES_DEBUG_CALLBACKS=1 to log a stack trace for every callback garbage-collected without .release().

    release() can be called from inside the JavaScript function, also while C is still running and may call the pointer again (a qsort comparator, an enumeration callback): it does not throw. From then on the trampoline returns zero without running JavaScript. If a JavaScript callback is running when release() is called, the trampoline is freed only when the callback is garbage-collected, so the C code still running can call it safely; otherwise it is freed at once. A threadSafeCallback() keeps its trampoline until it is garbage-collected, since other threads may be inside it at any time (the same holds for a callback() that another thread has called by mistake). After release(), reading .pointer (or _as_parameter_) throws Callback has been released (ThreadSafeCallback has been released), and passing the released callback, or a CFUNCTYPE instance over it, as an argument throws instead of passing a dangling address.

    Because callbacks use precompiled static AOT trampolines in .text from aotffi (with no runtime executable memory allocation), a Node.js process shares a fixed pool of 4,096 trampoline slots across the main thread and any worker_threads (configurable at build time with -DCTYPES_MAX_CALLBACKS=<1..65535> when building node-ctypes, or -DAOTFFI_MAX_CALLBACKS=<1..65535> when building deps/aotffi standalone). Exceeding the available slots throws Error: Failed to allocate FFI closure. Calling callback.release() outside an active callback returns its slot to the pool immediately; a threadSafeCallback() returns its slot once the wrapper has been garbage-collected, its ThreadSafeFunction queue has finalized, and any in-flight native trampoline call has returned.

    Callbacks invoked by native threads need threadSafeCallback(): the JavaScript function runs on the main thread, and the calling thread waits for its result (several threads can call it at the same time; each gets the result of its own call, 0 if the function throws). Like a timer, a thread-safe callback keeps the event loop alive until released; .unref() lets the process exit when nothing else is pending (calls are still delivered while it runs), .ref() restores it:

    const onEvent = threadSafeCallback((code) => console.log("event", code), null, [c_int]).unref();
    startWorker(onEvent); // a native library calling onEvent from its own thread

    Never wait synchronously for a thread that calls a threadSafeCallback. The callback can only run when the JavaScript thread is free. A synchronous call that waits for that thread (WaitForSingleObject, pthread_join, a C API that starts a worker and joins it) blocks the JavaScript thread, so the two threads wait for each other: the wait ends only on its timeout, and never with INFINITE. CPython does not have this problem, because it releases the GIL during a foreign call. Make the waiting call asynchronous:

    const thread = CreateThread(null, 0, onEvent, null, 0, null);
    await WaitForSingleObject.callAsync(thread, INFINITE); // the JS thread stays free

    callOn(executor, ...) works the same way. Calls from the JavaScript thread itself (for example a synchronous C call that invokes the callback before returning) run the function directly and do not wait.

    When the environment that owns a threadSafeCallback is closing (a worker is terminated, or the process exits) while a native thread still calls it, the call returns zero at once instead of waiting for the JavaScript thread, and getLastError() reports thread-safe callback called while its environment is closing; returned zero. A plain callback() invoked from a thread other than its own also returns zero and records an error.

    For an embedding runtime that must detach its native thread state before waiting, the optional fourth argument can be { abi, nativeContext: { suspend, resume, onError, notify? } } instead of the existing ABI string. Each hook accepts a ctypes native function, a low-level function handle, or a nonzero BigInt function address:

    const onRequest = threadSafeCallback(handleRequest, c_int, [c_int], {
    nativeContext: {
    suspend: runtime.func("save_context", c_void_p, []),
    resume: runtime.func("restore_context", null, [c_void_p]),
    onError: runtime.func("install_error", null, [c_void_p]),
    notify: runtime.func("wake_host", null, []),
    },
    });

    Function objects resolve through _as_parameter_ or address once, when the callback is constructed. The hooks are called directly using the default C ABI; the function wrapper's JS converters and errcheck are not invoked:

    • void *suspend(void) runs on a foreign caller before queueing.
    • void resume(void *) restores that caller's saved state after dispatch, including queue failure or environment shutdown. Neither hook runs on the Node host fast path.
    • void onError(void *) consumes an opaque error pointer on the original caller thread, after restoration. During the JS callback, use callback.setNativeError(pointer) once and return the native API's required error sentinel (NULL, -1, etc.). Error payloads belong to each invocation, including concurrent and nested calls; JS exceptions are still reported as documented above.
    • Optional void notify(void) runs on the foreign caller after successful queueing, while its native state is detached. It may wake the host through the consumer's runtime, but must not execute JavaScript itself.

    callback.drain() executes a snapshot of pending calls on the owning Node thread, returning the number it claimed. Each call executes at most once, whether the TSFN or a drain gets there first. Delayed TSFN deliveries retain only the shared request state and do not touch completed calls' native arguments. The consumer must provide a safe way to reenter the host and call drain(); calling it before entering a blocking native wait is not sufficient.

    Hooks must not throw or execute JavaScript. Plain JS functions and known JS-backed callback wrappers are rejected; an address cannot prove a function's signature, validity or implementation. Supplied function objects are retained by the native dispatcher through release and queued delivery cleanup. This does not prevent explicitly closing their libraries or releasing their underlying resources; raw addresses carry no owner. Keep the callback and the hook libraries alive until all native calls have returned; explicit release is rejected while a native-context call is active. These hooks do not acquire the host runtime context, pump a blocked host event loop automatically, or implement interpreter ownership/subinterpreters. The host JS handler must acquire/release its own runtime context around native API operations. The ordinary callback path is unchanged when no hooks are supplied.

    Both callback implementations store narrow integer results in a complete 64-bit ABI return word (AbiWord), with the declared signedness; failures zero that complete slot. Floating-point results retain their own storage width. The native Callback / ThreadSafeCallback classes also expose getPointer(), which throws after release.