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

    Pointers and memory

    import { POINTER, pointer, cast, c_int32, c_void_p } from "node-ctypes";

    // Pointer to an existing c-data instance (Python: pointer(x))
    const x = new c_int32(42);
    const px = pointer(x);
    px.contents.value; // 42 (Python: px.contents.value — a live c_int32)
    px[0]; // 42 (Python: px[0])
    px[0] = 100;
    x.value; // 100 (same memory)

    // View existing memory as a typed pointer
    const IntPtr = POINTER(c_int32);
    const p = IntPtr.fromBuffer(someBuffer);
    p[0];
    p[1];
    p[2]; // pointer arithmetic

    // cast() — Python: cast(ptr, POINTER(T))
    const q = cast(someBuffer, POINTER(c_int32));
    const r = cast(addressAsBigInt, POINTER(MyStruct));

    A POINTER(T) restype returns a pointer object, and a NULL pointer (return value or struct field) is null — where Python returns a falsy pointer.

    To hand a raw address to a function, use c_void_p as the argtype, or cast(address, POINTER(T)) for a POINTER(T) parameter: as in Python, a POINTER(T) parameter rejects an integer address with ArgumentError (expected LP_T instance instead of int). As in Python, values that cannot be converted (a plain JS function, an object, a non-pointer scalar instance such as new c_int(5)) raise ArgumentError instead of passing NULL; pass byref(x) for the address of an instance. As in CPython, a JS string given to a c_void_p parameter is passed as a NUL-terminated wchar_t * (c_void_p.from_param(str) is a c_wchar_p), while a Buffer (Python bytes) is passed as its bytes, so a char *. Any TypedArray, DataView or ArrayBuffer is passed as its memory.

    The c_void_p constructor, .value and fields take only an integer or BigInt address, a boolean or null, as in CPython. Use addressof(x) or cast(buffer, c_void_p) to store the address of a Buffer or an instance.

    Declared POINTER(T) parameters reject incompatible ctypes instances, arrays and pointer types before entering C. Compatible subclasses and arrays are accepted, and a matching scalar/structure is passed by reference. These implicit scalar/array/NULL conversions apply to direct arguments only. To adapt one of these values through _as_parameter_, return an explicit compatible pointer or byref value instead, as in CPython. An explicit cast() changes the pointer type. Raw Buffer/TypedArray/ArrayBuffer memory remains a node-ctypes extension; use c_void_p for portable raw-memory code.

    byref(value, byteOffset = 0) preserves the original owner and supports signed byte offsets. In-range references remain Buffer views; references outside the object's byte range carry an address and owner. As with raw addresses, the caller must ensure such memory is valid before dereferencing. Function pointers read from fields or obtained from FFI bindings can be assigned back to fields/arrays and passed as pointer arguments. Bare JS functions still require callback() / a prototype-created callback.

    A structure that points to itself, or to a type declared later, uses a thunk: POINTER(() => Node) resolves Node when the pointer type is first used. CPython's incomplete pointer types work too (deprecated in Python 3.14, so they emit a DeprecationWarning once per process):

    const lpcell = POINTER("cell"); // the same type for every POINTER("cell")
    class cell extends Structure {
    static _fields_ = [
    ["name", c_char_p],
    ["next", lpcell],
    ];
    }
    lpcell.set_type(cell); // or SetPointerType(lpcell, cell), also deprecated
    POINTER(cell) === lpcell; // true: cell.__pointer_type__ is lpcell

    Before set_type(), creating an instance throws TypeError Cannot create instance: has no _type_ (from_buffer() / from_address() and fields still work), and as a parameter type it takes null and raises ArgumentError expected LP_cell instance instead of X for other values; after it, the type is complete everywhere it is used. set_type() can also retarget a pointer type, and sets T.__pointer_type__ only when T has none.

    As in CPython 3.14, T.__pointer_type__ holds the type POINTER(T) returns: it is set by the first POINTER(T) (undefined before, not inherited by subclasses), and you can assign or delete it.

    // Zero-copy view over a Node Buffer (Python: Structure.from_buffer)
    const r = RECT.from_buffer(packet, 16);

    // Wrap an externally-allocated pointer (Python: Structure.from_address)
    const r2 = RECT.from_address(malloc_result);

    // Bind a C-exported global (Python: c_int.in_dll)
    const tz = c_int32.in_dll(libc, "_timezone");

    // Raw bytes at an address (Python: (c_ubyte * n).from_address(addr));
    // `bytes._buffer` is a Buffer over that memory, as Python's memoryview()
    const bytes = array(c_uint8, 64).from_address(malloc_result);
    const view = new Float32Array(bytes._buffer.buffer, bytes._buffer.byteOffset, 16);

    For Structure and Union subclasses, from_buffer(), from_address() and in_dll() return live views. from_buffer_copy() instead creates an independent copy of the bytes. None of these factories run the subclass constructor or its instance field initializers: obtaining a view does not reinitialize the pointee or the exported C variable. Use new T(...) when you want the constructor to run.

    Typed pointers read from fields or array elements, and views derived from them, retain their known memory owners. Typed assignments and from_buffer_copy() preserve known pointer references, including overlapping and self-copies. If C changes a pointer field before the copy, the copy uses the current address and does not keep the previous pointee alive through that field. The pointer slots are independent; the pointee itself is not copied.

    Raw copies (memmove(), Buffer methods) do not transfer ownership metadata. Likewise, from_address() given a raw address cannot discover its allocation or library: the caller must keep that memory valid. As in CPython, from_address() reads nothing when it creates the instance (only reading a value touches the memory), takes an integer address (a negative one wraps: from_address(-1) is at 2n ** 64n - 1n; out of the pointer range RangeError int too big to convert, a non-integer TypeError integer expected), and address 0 throws TypeError from_address: NULL address (CPython creates an instance there). in_dll() takes a string name (TypeError in_dll() argument 2 must be str, not int). Keeping a known owner alive does not take over responsibility for freeing externally allocated memory or explicitly releasing callbacks.

    memmove() and memset() return the destination address as BigInt, including zero-length operations (0n for a NULL destination with count zero). Counts must be non-negative safe integers. As in CPython, memset() takes the fill value modulo 256 (a Number, BigInt or boolean; other values raise ArgumentError), and a JS string source of memmove() is a wchar_t *. Each argument also takes an instance of its Python argtype (or an object whose _as_parameter_ is one): a c_int fill value, a c_size_t count, a c_int size for string_at() / wstring_at(); other C data, and a count that is not an integer, raise ArgumentError (argument 3: TypeError: 'float' object cannot be interpreted as an integer). Copies/fills involving JS memory still stop at its end; raw native addresses remain the caller's responsibility. Scalar from_buffer() / from_buffer_copy() validate byte size and offset before producing an instance and accept Buffer, typed views and ctypes memory. Offsets may be Numbers, BigInts or booleans; the errors are CPython's (RangeError offset cannot be negative / Buffer size too small (2 instead of at least 4 bytes), TypeError memoryview: a bytes-like object is required, not 'int').

    POINTER(T).from_buffer(buf), from_buffer_copy(), from_address(addr) and in_dll(lib, name) follow CPython: the memory is the pointer slot itself (p.contents = x writes the address of x into buf). The Node POINTER(T).fromBuffer(buf) / fromAddress(addr) instead create a pointer to that memory. Array types and CFUNCTYPE prototypes have in_dll() too (a prototype reads the stored function pointer once).

    Pointers into memory that node-ctypes knows are bounds-checked: a pointer into a ctypes instance (pointer(arr[0]), cast(byref(a, 8), POINTER(T))) can reach its whole allocation ([2], [-1]), but an instance you create with from_buffer() over a subview of a larger Buffer is limited to that subview.

    callAsync() and callOn() pass the memory of a Buffer, typed array, DataView or ArrayBuffer argument in place, exactly like synchronous calls (and like Koffi): C receives the address of the view itself (addressof(view)), its writes are in the view when the promise settles, and the result conversion and errcheck already see them. The same holds for create_string_buffer() results, ctypes arrays, and structures or scalars passed with byref(), pointer() or by implicit reference.

    node-ctypes keeps the argument objects alive until the call settles, but the memory stays yours while C runs on another thread. Until the promise settles:

    • do not detach it (ArrayBuffer.prototype.transfer(), a postMessage / structuredClone transfer list), resize it, or modify it concurrently from JavaScript;
    • C must not keep the pointer after the call returns, unless you keep the memory alive (and attached) for as long as C uses it.

    Node-API cannot prevent the detach, so node-ctypes reports it instead: a call whose view argument was detached meanwhile, or left out of bounds by shrinking its resizable ArrayBuffer, rejects with buffer argument: memory was detached (transfer() or a transfer list) or shrunk out of bounds while the native call could use it; .... Native code may already have read or written memory that was released, so the result is not reliable. The check covers views passed as arguments, not addresses stored inside structures or obtained with addressof(): keep the memory behind them alive, and attached, until the call settles.

    For memory that C shares with JavaScript or with callbacks while it runs (a flag that C polls, a progress counter), use a SharedArrayBuffer view: it cannot be detached.

    Memory that was already detached, or a view out of bounds of a resizable ArrayBuffer that was shrunk, has no bytes of its own (it reports byteLength 0). Passed where memory is taken (a pointer, c_char_p or c_wchar_p argument, sync or async; addressof, memmove, memset, readValue / writeValue, string_at, from_buffer, cast, memoryview_at) it throws a TypeError (memory of a detached or out-of-bounds ArrayBuffer cannot be used; an ArgumentError for a function argument), never NULL or the base address of the buffer. A valid empty view keeps its address.

    Synchronous calls follow the same rule. A synchronous call during which a JavaScript callback detached an argument throws argument N: memory was detached ... after native code returns.

    • sizeof(type) / alignment(type) — in bytes (pointer size for function pointers and library functions)
    • addressof(obj) → BigInt; takes ctypes instances, memory and function pointers, not integers (TypeError)
    • byref(obj, byteOffset = 0) — lightweight reference with a signed byte offset
    • cast(ptr, type) — reinterpret a pointer as another type; an integer source is masked to 64 bits (cast(-1, c_void_p).value is 2n ** 64n - 1n), a boolean is 1/0, a JS string a wchar_t *; NaN, fractions and JS arrays raise ArgumentError
    • memmove(dst, src, n) / memset(dst, val, n) — buffers, ctypes instances, pointers or addresses; return the destination address as BigInt
    • readValue(ptr, type, offset?) / writeValue(ptr, type, val, offset?) — a structure type takes an instance (expected S instance, got bytes for a Buffer); offset is a non-negative safe integer Number (TypeError: offset must be a number, not string for another type, RangeError: offset must be a non-negative safe integer (got 1.5) for NaN, Infinity, fractions and negative values)
    • create_string_buffer(init, size?) / c_buffer / create_unicode_buffer(init, size?) — with .value (and .raw); both results are Buffers, so length counts bytes (Python's len() of a create_unicode_buffer() counts characters: use sizeof(buf) / sizeof(c_wchar))
    • string_at(addr, size?) / wstring_at(addr, size?) — exactly size units, or up to the NUL
    • memoryview_at(ptr, size, readonly = false) — a live view of size bytes (see below)
    • resize(obj, size) — grows the memory of an instance that owns it (see below)

    string_at returns a lossless Latin1 string, with or without a byte count: Buffer.from(string_at(addr, n), "latin1") recovers all n original bytes, including embedded NUL and invalid UTF-8; without a count it reads up to the first NUL. wstring_at counts native wide-character units. As in CPython, the size is a C int: a Number or a BigInt taken modulo 2**32 (2 ** 34 is 0, 2n ** 64n - 1n is -1; a value that wraps to another negative size, such as 2 ** 31, raises RangeError), or a boolean; a JS string source is read as a wchar_t *, and wstring_at(null, 0) is ""; other sources raise ArgumentError ('float' object cannot be interpreted as ctypes.c_void_p). A string longer than a JS string can hold (about 2**29 characters on 64-bit Node.js) throws RangeError Invalid string length: N units exceed the maximum JS string length after reading only its first character.

    create_string_buffer() and create_unicode_buffer() check their arguments as CPython: a null size is computed from init, an integer init ignores size, a negative size throws RangeError Array length must be >= 0, not -1, a non-integer size TypeError can't multiply sequence by non-int of type 'float', and an unsupported init TypeError. The .value setter of a string buffer takes bytes or a string (bytes expected instead of int instance), .raw bytes-like memory (a bytes-like object is required, not 'int'); the .value of a unicode buffer takes only a string.

    memoryview_at(ptr, size, readonly = false) (CPython 3.14) views size bytes at ptr, which takes what a c_void_p parameter takes: an address, an array, a pointer, byref(x), a c_void_p instance or a Buffer. As in CPython, a structure, union or other scalar instance (also as _as_parameter_) throws ArgumentError argument 1: TypeError: 'S' object cannot be interpreted as ctypes.c_void_p: pass byref(s). The view is live: writes through it change the memory, and C writes are visible in it.

    const x = new c_int32(5);
    const view = memoryview_at(byref(x), 4); // a Buffer; view.readonly === false
    view[0] = 7; // x.value === 7
    const ro = memoryview_at(byref(x), 4, true);
    ro[0]; // 7
    ro[0] = 1; // TypeError: cannot modify read-only memory

    A writable view is a Buffer over the memory. JavaScript has no read-only Buffer, so a read-only view is a Proxy of one: index writes and mutating methods (fill, set, write*, swap*, and, where available, setFromHex and setFromBase64) throw TypeError cannot modify read-only memory, .buffer and .parent are undefined, and T.from_buffer(ro) throws TypeError underlying buffer is not writable (from_buffer_copy() works). Subviews and the view passed to iteration callbacks remain live and read-only. Without external buffers (Electron, NODE_CTYPES_NO_EXTERNAL_BUFFERS=1) a view of native memory is also a Proxy, which re-reads the memory before reads and writes it back after writes. In-place decoders also write back a valid prefix if decoding then throws SyntaxError, as on a regular Buffer. Buffer.from(view) copies any view. A negative size throws RangeError memoryview_at: size is negative (or overflowed): -1, and a NULL address with a non-zero size RangeError NULL pointer access.

    resize(obj, size) (CPython ctypes.resize) gives an instance more memory, keeping its contents; the new bytes are zero and sizeof(obj) reports the new size, which is how CPython handles variable-sized structures:

    const arr = ARRAY(c_int32, 1)(42);
    resize(arr, 4 * sizeof(c_int32)); // sizeof(arr) === 16
    cast(byref(arr), POINTER(c_int32))[3]; // 0

    The size must be at least the size of the type (RangeError minimum size is 4), and the instance must own its memory: an instance from from_buffer() or from_address(), a field, an element or a pointer's contents throws RangeError Memory cannot be resized because this object doesn't own it. Pointer instances are resized as in CPython (pointer(x), POINTER(T)(), cast() and from_buffer_copy() results own their memory); create_string_buffer() / create_unicode_buffer() Buffers cannot be resized (RangeError; CPython resizes them). The instance moves to new memory: pointers, byref() and views taken before still refer to the old memory, so take them again after resize() (in CPython they dangle).

    Electron does not allow Buffers over memory that V8 did not allocate, so a Buffer view of native memory cannot exist there. node-ctypes detects this when it loads (EXTERNAL_BUFFERS is false) and keeps the same API:

    • instances on native memory (from_address, in_dll, pointer.contents, p[i], pointer fields) work on a copy that is re-read before every access and written back after every assignment, so they still see what C writes and C sees what JavaScript writes;
    • passed to a C function, addressof(), pointer(), memmove() and memset(), such an instance uses the original address;
    • the _buffer of such an instance is the copy: a typed array or Buffer method over it does not read or write native memory. Use the instance (arr[i], s.field) or memmove().

    Only the bytes of the accessed field are copied, one native call per read or write; instances on ordinary Buffers (new Point(), new c_int(5)) do not need this native-memory synchronization. Set NODE_CTYPES_NO_EXTERNAL_BUFFERS=1 to run in this mode on Node.js.