import { Structure, Union, array, c_int32, c_uint32, c_float, c_char } from "node-ctypes";
class Rect extends Structure {
static _fields_ = [
["x", c_int32],
["y", c_int32],
["w", c_int32],
["h", c_int32],
];
}
class Value extends Union {
static _fields_ = [
["i", c_int32],
["f", c_float],
];
}
// Bit fields: [name, type, bitCount]
class Flags extends Structure {
static _fields_ = [
["enabled", c_uint32, 1],
["mode", c_uint32, 3],
["priority", c_uint32, 4],
];
}
// Arrays: elementType * count (Python: `c_int32 * 5`)
const IntArr5 = array(c_int32, 5);
const arr = IntArr5(1, 2, 3, 4, 5); // Python: (c_int32 * 5)(1, 2, 3, 4, 5)
// char arrays read and write as strings (Python: bytes)
const name = array(c_char, 16)();
name.value = "node"; // .value / .raw as in Python
array(type, n) reuses the same type while it is alive. Instances, function
signatures and containing types keep their array types alive; the cache itself
does not. Unused array types and their length entries can be garbage-collected,
including arrays of builtin element types.
An array type in argtypes is passed by address, as in C and Python
(fill.argtypes = [c_int32 * 4]). As in Python, the argument must be an
instance of an array with the same element type and length; a Buffer or a
typed array is also accepted as its memory. Other values raise
ArgumentError.
CPython's class T(Array) form works with the Array export (CPython's
abstract ctypes.Array, not the native ArrayType; import it as CArray
to keep the global Array):
import { Array as CArray, c_int } from "node-ctypes";
class Int13 extends CArray {
static _type_ = c_int;
static _length_ = 13;
}
const a = new Int13(1, 2, 3); // sizeof(a) === 52, a instanceof Int13
_type_ and _length_ are checked when the class is first used: a missing
one throws AttributeError class must define a '_length_' attribute
('_type_'), a non-integer length TypeError
The '_length_' attribute must be an integer, a negative or too large one
(above Number.MAX_SAFE_INTEGER) RangeError. As in CPython such a class
is its own type: fields, parameters, array elements and p[i] of a
POINTER(Int13) accept only its instances (or those of its subclasses), not
a same-shape ARRAY(c_int, 13) instance (TypeError
incompatible types, c_int32_Array_13 instance instead of Int13 instance).
Array itself cannot be instantiated (TypeError abstract class), and
every ctypes array is instanceof Array. Array instances expose _type_ and
_length_ (a._length_ === 13), as do the array types, and an array type
larger than Number.MAX_SAFE_INTEGER bytes throws RangeError
array too large.
Builtin numeric scalars accept numbers, booleans and BigInt; integers wrap to
their C width, but reject non-integral or non-finite numbers. Use BigInt when
the original integer needs more precision than a JS number can represent.
No argument, or undefined in a constructor, initializes zero. Explicit
null, strings and arbitrary objects are not implicit numeric conversions.
Assigning a scalar instance to a field or passing it to a declared numeric
argument requires a compatible type. The documented numeric-pointer argument
extensions below are unchanged.
c_bool and wintypes.VARIANT_BOOL convert values with Python's truth
rules: NaN is true, a scalar instance is true when its bytes are not all
zero (so new c_double(-0.0) is true), a NULL pointer instance and an empty
array, Buffer or JS array are false.
VARIANT_BOOL stores true as -1, and its results and callback arguments
are booleans. Boolean bitfields normalize before masking and read as booleans;
writing one changes only its own bits (CPython rewrites the whole storage
unit, see Python ctypes parity).
Nested structs, anonymous fields (static _anonymous_ = ["data"]),
explicit packing (static _pack_ = 1), minimum alignment
(static _align_ = 16), self-referential pointers (POINTER(() => Node))
and Structure subclasses that add fields follow Python's layout rules.
The layout of bit fields follows Python's _layout_: "gcc-sysv"
by default, "ms" on Windows or with _pack_. Bit fields wider than 53
bits read as BigInt. A bit width may be a Number, a BigInt or a boolean; a
non-integer width throws TypeError an integer is required. A bit field of
an explicitly swapped type (c_uint16.__ctype_be__) keeps that byte order
in a native structure.
_fields_ is checked as in CPython, after the layout attributes (_pack_,
_align_, _layout_): an entry that is not a (name, type) pair or
(name, type, bits) triple throws RangeError
_fields_ must be a sequence of (name, C type) pairs or (name, C type, bit size) triples,
a ctypes instance in place of a type TypeError
type of field 'a' must be a C type, _fields_ = null TypeError
'NoneType' object is not iterable, and a negative _pack_ RangeError
_pack_ must be a non-negative integer. An _anonymous_ field must be a
structure or union (AttributeError
type object 'c_int32' has no attribute '_fields_'); the fields are promoted
in _anonymous_ order, so the last listed field wins a name, and the fields
of nested anonymous structures are not class attributes of the outer class.
As CPython, an _anonymous_ name that an earlier promotion replaced with a
field of a simple type throws that AttributeError too. _anonymous_ must
be a sequence (TypeError _anonymous_ must be a sequence; a string is the
sequence of its characters).
_fields_ is final once the class is used, as in CPython: assigning it
again throws AttributeError _fields_ is final. A class is final after
an assignment S._fields_ = [...], and after its first instantiation,
from_buffer() (or another factory) or use as a field type; using a subclass
finalizes its bases too. sizeof() of a class without _fields_ leaves it
open, as in CPython. A class declared with static _fields_ is checked and
finalized when it is first used (JS sets static fields after the class
body). A structure or union that contains itself
(R._fields_ = [["r", R]], directly or through other structures) throws
AttributeError Structure or union cannot contain itself when it is
materialized; use a pointer to it instead.
A class that declares _abstract_ (static _abstract_ = true; as in
CPython any value counts), like the Structure, Union and SimpleCData
bases themselves, cannot be instantiated or used with
from_buffer(), from_buffer_copy(), from_address() or in_dll():
TypeError abstract class. Subclasses of it that do not declare
_abstract_ are ordinary classes.
Each field is a CField class attribute (Rect.w.offset, .size,
.byte_offset, .byte_size, .bit_offset, .bit_size, .is_bitfield,
.is_anonymous, .type, .name), available before any instance exists,
and Rect.w instanceof CField. As in CPython the CField constructor is
internal: it takes { name, type, byte_size, byte_offset, index, _internal_use: true }
(plus bit_size / bit_offset for a bit field) and throws RangeError
for a byte_size that is not the type size
(byte size of field 'a' (2) does not match type size (1)) or a bit field
that overflows its type (bit field 'x' overflows its type (2 + 7 > 8)).
delete of a .value or .raw of a ctypes character array, of p[i] or
of p.contents throws TypeError (can't delete attribute,
cannot delete attribute, Pointer does not support item deletion), as
in CPython (where del arr.raw is an AttributeError).
A Union subclass without its own _fields_ keeps the base layout in both
libraries. If it declares _fields_, even [], node-ctypes still reserves
space for every inherited field. CPython can instead report a smaller
sizeof while retaining the inherited field descriptors. The difference
also affects array stride and the offsets of subsequent structure fields.
If both libraries must use the same layout when adding a smaller member,
declare a new union with the base union and the new member as alternatives.
Assignments are checked as in CPython. A nested Structure / Union field or
a structure array element takes an instance of its type or a tuple (a JS
array of field values), and, as a Node extension, a plain object of named
field values; raw Buffers, other structures, arrays and scalars throw
TypeError. An array field takes the same array type (with the same byte
order) or a tuple. A c_char * n field (and initializer) takes bytes (a
Buffer or a Uint8Array) or a string; other typed arrays, DataView, JS
arrays, numbers and null throw TypeError (expected bytes, Int16Array found), as do the .value setter of a c_char array
(bytes expected instead of Int16Array instance) and its .raw setter for
non-memory values (a bytes-like object is required, not 'list'; .raw
takes any typed array or DataView as bytes). A c_wchar * n field and the
.value of a c_wchar array take only a string
(unicode string expected instead of int instance). A c_char * n field
stores the bytes up to the first NUL, plus a NUL when there is room
(CPython strlen). The .value of a c_char array rejects ctypes
instances and byref() (bytes expected instead of _ctypes.CArgObject instance),
and .raw takes the memory of any ctypes instance but not byref()
(a bytes-like object is required, not '_ctypes.CArgObject'). A
POINTER(T) field
takes a POINTER(T) instance, null, or a ctypes array of a compatible
element type (its address is stored and the array kept alive); numbers,
BigInts and Buffers throw TypeError. A CFUNCTYPE field takes an instance
of its prototype; null throws TypeError as in CPython, and a field
holding NULL reads as null; its CField.type is the prototype itself.
Tuple and plain-object assignments are atomic: when an element fails, the
field keeps its previous value.
Reading a nested Structure or Union field returns a fresh instance of the
declared class without running its constructor. Two reads of rect.origin
give different objects at the same address: an ordinary JS property attached
to one is not visible on the other, but writes to C fields are. Assigning a
new value to rect.origin overwrites those bytes, so existing views see the
replacement too. Each view keeps its container alive, whether obtained from
rect.origin, rect.get("origin") or rect.getFields(["origin"]).origin.
The container does not retain discarded views. If a loop accesses the same
field repeatedly, keep const origin = rect.origin outside the loop to reuse
the view without copying any bytes.
For arrays of Structure or Union classes, indexing and iteration also
return fresh views over the element's bytes without running its constructor.
Keeping one such view keeps the array alive; the array does not retain
discarded views. If items is such an array inside a Structure or Union,
keeping either holder.items or holder.items[i] also keeps holder alive.
Character array fields read as strings, not views.
_pack_ follows Python's integer conversion and permits zero and non-powers
of two (for example 3) with the MS layout. An explicit _pack_, including
zero, is incompatible with "gcc-sysv". Layouts with non-power-of-two
alignment can be used for memory serialization but are rejected as native
by-value signatures: they do not describe a valid C ABI alignment.
Structures and unions passed or returned by value keep this layout, also
with _pack_: as with GCC and clang, a structure with misaligned fields is
passed in memory on x86-64 System V (Linux, macOS Intel), where Python
ctypes passes it in registers and the called function reads wrong values.
A matrix field such as ARRAY(ARRAY(Cell, 2), 2) stays inline when its
structure is passed or returned by value. On ARM64, if Cell contains just
one c_float, the four floats form a homogeneous floating-point aggregate.
Node follows the C calling convention here: in this case CPython ctypes
disagreed with a typed C caller for both arguments and results on the tested
Windows and Linux ARM64 builds.
Each returned structure or union owns a snapshot of its value, including
results declared with functional struct() / union() definitions. Array
views, nested composites and union getters remain valid after later calls,
reentrant conversion or errcheck, and concurrent callAsync() jobs.
Mutating one result does not modify another result's value storage.
When the return type is a Structure or Union class, the result has that
class's prototype and the bytes returned by C. As in CPython, materializing
the result does not call the user's constructor; JavaScript instance field
initializers do not run either. Use _check_retval_ to validate or transform
the result. Its return value is passed to the function's errcheck, if set.
Explicit new still runs the constructor normally.
Synchronous low-level native struct_buffer results use borrowed, reusable
storage, so the wrapper copies the bytes before either hook can reenter the
function. With callAsync() or callOn(), each native completion already
owns its buffer; a class result uses it without a second copy. This is not a
deep copy through pointers: pointer fields can still refer to the same external
memory. Explicit definition.toObject(buffer) keeps its buffer-view behavior.
Low-level native StructType descriptors are builders only until consumed.
Adding a descriptor as a field, constructing an ArrayType from it (even at
length zero), preparing a function/callback signature, or creating/reading a
native value finalizes the captured layout and its dependencies.
addField() then throws instead of changing sizes, offsets or FFI metadata
already in use. Build a new descriptor for a different layout.
getSize() and getAlignment() alone leave an unused builder open; an
outer builder can still receive fields after it captures a finalized child.
Direct by-value self-reference is rejected. Pointers do not capture or
finalize the pointed-to layout.
class NetHeader extends BigEndianStructure {
static _fields_ = [
["magic", c_uint32],
["length", c_uint32],
];
}
const h = new NetHeader();
h.magic = 0x12345678; // stored as 12 34 56 78 on the wire
LittleEndianStructure, BigEndianUnion, LittleEndianUnion work the
same way. Byte order is per-class — nested structs keep their own. As in
CPython, the CField of a field with a non-native byte order names the
swapped type: NetHeader.magic.type is c_uint32.__ctype_be__
(<ctypes.CField 'magic' type=c_uint32_be, ofs=0, size=4>) on a
little-endian host, also for bit fields and arrays.
As in CPython, a non-native byte order rejects field types that have no
swapped form: pointers, CFUNCTYPE, c_void_p, c_char_p, c_wchar_p,
c_wchar and arrays of them throw
TypeError: This type does not support other endian: <class 'ctypes.c_void_p'>.
A byte-swapped structure checks the byte order of every field before the
layout. An array field of such a structure has the swapped element type as
_type_ (c_int32_be) and accepts instances of that swapped array type.
Primitive arrays also follow their containing class's byte order, recursively for multidimensional arrays, including floats and wide-character arrays. Arrays of structures keep the element structure's own byte order. The same array type can be shared with native/little-endian containers without being modified. Raw Buffer and typed-memory copies still copy bytes, not values converted between byte orders.
struct({...}) / class extends Structure — composite struct types; get() / set() of a struct() / union() definition throw AttributeError Unknown field: x for an unknown nameclass extends Union — union typesarray(type, n) / ARRAY(type, n) — Python's type * n; callable: array(c_int, 3)(1, 2, 3); elements can be simple types, structures, arrays, POINTER(T) and CFUNCTYPE typesPOINTER(type) — pointer-to-type; accepts a thunk POINTER(() => T) or a name POINTER("T") (an incomplete type completed with set_type(T), see Pointers and memory); POINTER(T) is kept in T.__pointer_type__class extends Array — CPython's class T(Array) with _type_ and _length_ (see above)pointer(instance) — pointer to an existing c-data instanceCFUNCTYPE(restype, ...argtypes) — function pointer type: proto(jsFn) (callback), proto(address), proto([name, lib], paramflags?) (Python: proto((name, dll), paramflags)); proto() / proto(0) is a NULL function pointer (address 0n); instances are instanceof proto, the prototype is named CFunctionType, and proto.in_dll(lib, name) reads an exported function pointerWINFUNCTYPE(restype, ...argtypes) — __stdcall callback typedefineStruct({...}) — typed-TS variant of structT.from_buffer(buf, offset?) — zero-copy view (the offset may be a Number, a BigInt or a boolean; RangeError offset cannot be negative / Buffer size too small (N instead of at least M bytes))T.from_buffer_copy(buf, offset?) — independent copyT.from_address(addr) — wrap raw pointerT.in_dll(lib, name) — bind to exported global; also on array types, POINTER(T) and CFUNCTYPE prototypes; a missing symbol throws RangeError symbol 'name' not foundT.from_param(v) — the default argument converter of Structure / Union, scalar, POINTER(T), array and CFUNCTYPE types: returns an instance of T (or the _as_parameter_ it resolves to; POINTER(T) also takes byref(), a compatible array and an instance of T, as CPython), otherwise throws TypeError; a subclass can override it and call the base class's.obj._as_parameter_ — an instance property that replaces the object when it is passed as an argument (see Libraries and functions)new T(...values) initializes the fields in order, as Python's T(...): new T(buffer) copies the Buffer into the first field. Use T.from_buffer(buffer) to view existing memory.