node-ctypes follows CPython 3.14 ctypes. When the two differ, the goal is to
match CPython, even when that changes existing node-ctypes behavior; the
changelog marks those changes as breaking. This page lists
the differences that remain.
Structs, unions, bit fields (_layout_ "gcc-sysv" / "ms"), anonymous
fields, _pack_, _align_, subclasses of structures and unions, nested layouts,
structures and unions by value (a struct restype returns an instance),
arrays (also of arrays, pointers and function pointers), pointers and
pointer arithmetic (also POINTER(POINTER(T))), callbacks (CFUNCTYPE /
WINFUNCTYPE, also as struct fields), prototype((name, dll), paramflags),
COM methods prototype(vtblIndex, name, paramflags?, iid?) (Windows),
from_buffer / from_buffer_copy / from_address / in_dll,
_as_parameter_ / from_param, paramflags out-params, errcheck,
use_errno / use_last_error, OleDLL + HRESULT auto-raise,
BigEndianStructure / LittleEndianStructure and union variants,
__ctype_be__ / __ctype_le__, CField (class attributes and the class),
_abstract_, Array subclasses (_type_ / _length_), c_longdouble,
incomplete pointer types (POINTER("Name"), set_type(),
SetPointerType()) and __pointer_type__, resize(), memoryview_at(),
util.find_library() / util.dllist(), ctypes.wintypes,
lib[name] (as lib.__getitem__(name)), keepalive of objects assigned to
fields (_objects).
The tests use the same mapping in both languages (tests/README.md):
T(value) is new T(value), (T * n)(...) is ARRAY(T, n)(...), a tuple
is a JS array, None is null, bytes is a Buffer as input.ValueError and IndexError from ctypes are RangeError (for
example NULL pointer access, an invalid _layout_ or bit-field width,
too many array initializers). Other exception types keep their name:
TypeError, ArgumentError (a TypeError subclass), AttributeError.3.0 is 3: JS cannot tell them apart), so it is passed as a C
int without argtypes; use new c_double(x) for a double. Integer types
reject non-integral numbers (3.7, NaN) as Python rejects floats.
c_long, c_ulong and 64-bit values are read as BigInt on every platform.paramflags function are one plain object as the
only argument: fn({ hWnd: h }). All its keys must name input parameters;
otherwise the call raises TypeError with CPython's message for an unknown
keyword, call takes exactly N arguments (M given). A missing input raises
required argument 'x' missing. When the first input is a Structure or
Union, a plain object whose keys are not all input names is the value of
that structure.lib[name] is lib.__getitem__(name). A library member (close, func,
symbol, callback, path, loaded, get_errno, get_last_error, and
the _-prefixed internals) wins over a C export with the same name in
lib.name, because JS cannot tell lib["x"] from lib.x; use
lib.__getitem__("close") or lib.func("close", ...) for such an export.
As in CPython, reading a missing export throws AttributeError, and
name in lib works like hasattr. Dunder names and JS protocol probes
(then, toJSON, ...) return undefined. A JS property key is always a
string, so lib[1] looks up the export named "1": use
lib.__getitem__(1) for Python's ordinal lookup lib[1] (Windows).ctypes.Array is the Array export: importing it under that name shadows
the global Array in the module, so import { Array as CArray } and
class T extends CArray { static _type_ = c_int; static _length_ = 4 }
may be clearer. ctypes.util.dllist() is util.dllist(), and del x.a
is delete x.a.These are the remaining cases where the same Python-shaped code behaves differently.
.release() (or a using
declaration). GC cannot detect when C code still holds the pointer;
relying on it causes use-after-free.bytes results are JS strings: c_char values, c_char * n arrays and
fields, c_char_p and create_string_buffer().value decode UTF-8 where
Python returns bytes; .raw is a Buffer. Bytes that are not valid
UTF-8 become U+FFFD (a c_char_p result b"abc\xe4" reads as
"abc\uFFFD"). string_at() returns the bytes as a Latin1 string, with or
without a size (lossless: Buffer.from(s, "latin1")): use it for exact
bytes.Uint8Array is bytes for the .value of a c_char array or of
create_string_buffer(), as a Buffer is; CPython takes only bytes there
and rejects a memoryview.null: a POINTER(T) or CFUNCTYPE restype,
field or array element holding NULL reads as null, where Python returns a
falsy pointer or function object. POINTER(T)() still creates a NULL
pointer instance (p.isNull).P(), P(0) and cast(null, P) of
a CFUNCTYPE prototype P create a NULL function pointer, as in CPython,
but it is a JS function, so Boolean(P()) is true where bool(P()) is
False: test f.address === 0n. Calling it throws Error
exception: access violation writing 0x0000000000000000 (CPython: the same
OSError on Windows) on every platform.c_int32.name is
"c_int32", so ARRAY(c_int32, 3).name is "c_int32_Array_3" and
POINTER(c_int32).name is "LP_c_int32". CPython names the platform C
type (c_long_Array_3 on Windows, c_int_Array_3 on Linux). An incomplete
POINTER("Name") type is named LP_Name, also after set_type(T), as in
CPython.c_int / c_long (and c_uint / c_ulong, UINT / DWORD) are two
classes where long is 32-bit (Windows), where CPython has one. They are
interchangeable in arguments (also arrays of them as array parameters),
from_param, POINTER parameters, structure fields and array elements,
and __ctype_be__ gives the same
class; c_int === c_long is false. c_long values are BigInts there,
while c_long.__ctype_be__ (which is c_int.__ctype_be__) reads Numbers.from_param: c_int.from_param(5) returns a c_int instance
(CPython returns an opaque cparam object). POINTER(T), array and
CFUNCTYPE types have from_param too, with CPython's rules.from_param result is passed with the parameter's C type: for
a POINTER(T), array or c_void_p parameter, the result (an integer
address, null, a string, an instance, byref(), a Buffer or an
_as_parameter_ object) is passed as a pointer, where CPython passes a
result with its own C type. An integer instance (c_int32(7)) is passed at
pointer width, and a float result raises ArgumentError
(Don't know how to convert parameter N). The same holds for any object
with a from_param method used as an argtypes item (an adapter that is
not a ctypes type): its result is a pointer-sized parameter, where CPython
passes a float result as a double.class X extends c_int32.__ctype_be__ {} is native-order;
its __ctype_be__ is a new class named X_be (CPython reuses the name
X).fn.argtypes reads [] when unset, where CPython returns None.
Assigning null clears it, as in CPython.create_unicode_buffer() returns a Buffer, like
create_string_buffer(): its length counts bytes, where Python's len()
counts characters (sizeof(buf) / sizeof(c_wchar)). It keeps the Buffer
argument fast paths and Buffer interop. As Buffers, these results cannot
be passed to resize(), and delete buf.value is ignored (CPython raises
TypeError; it does for ctypes arrays here too). Their indices are the
Buffer's: buf[0] is a byte Number (CPython: a 1-byte bytes), and
buf[0] = "?" stores Number("?"), i.e. 0, where CPython stores b"?"
for b"?" and raises TypeError for a str. Assign byte values
(buf[0] = 0x3f), use buf.value / buf.raw, or use an
array(c_char, n) instance, whose items follow c_char.WinDLL / OleDLL functions check arity as CDLL: with argtypes,
extra arguments are passed and too few raise
this function takes at least N arguments (M given), where CPython
requires exactly N for non-cdecl functions
(this function takes N argument (M given)).POINT with fields phi and rho,
new POINT(2, 3, { phi: 4 }) throws TypeError too many initializers,
where CPython's POINT(2, 3, phi=4) raises
duplicate values for field 'phi', and new POINT(2, { phi: 4 }) gives
rho the object (TypeError must be real number, not dict). Use
either positional values or one object of field values.new S({ zz: 1 })
(Python S(zz=1)) throws AttributeError Unknown field: zz for
Structure, Union and defineStruct() classes, where CPython sets an
instance attribute. struct() / union() create() ignores the key at
runtime (the typings reject it), and their get() / set() of an unknown
field throw AttributeError.c_bool (or VARIANT_BOOL) bit field changes only its own
bits, as for the other integer types. CPython rewrites the whole storage
unit of a boolean bit field, clearing the neighboring bit fields: after
s.b = true; s.a = true on 1-bit fields a and b, the byte is 0x03
here and 0x01 in CPython.POINTER(c_char) parameters accept a JS string, passed as a
NUL-terminated UTF-8 char * as for c_char_p (also a from_param
result); CPython raises TypeError for a str.restype / argtypes of a function pointer instance are fixed:
assigning them on a CFUNCTYPE / WINFUNCTYPE instance (or a
paramflags function) throws TypeError, where CPython uses the new
value for that instance. Create the instance from a prototype with the new
signature, or use the library attribute (lib.name), whose restype and
argtypes can change.undefined. Writes outside the array,
negative indexes included, throw RangeError invalid index (CPython
wraps a negative index and raises IndexError invalid index beyond the
end). Use a.at(-1) and a.slice().slice, map, includes, …, as Python sequences); the Buffer methods
(readInt32LE, subarray, …) work on the bytes. delete arr.raw of a
character array throws TypeError cannot delete attribute, where CPython
raises AttributeError.s.inner = [1, "x"],
m[0] = [1, 2, 3, 4]) are thrown as they are (TypeError, RangeError),
where CPython wraps them in RuntimeError ((Inner) TypeError: ...).name, length,
prototype, Function.prototype members, library statics, internal type
markers such as _pointerTo or then) are not class attributes: use
S.fields to read their CField data. Instances still read and write them.p[i] and p.contents outside that memory throw RangeError, where
CPython reads or writes whatever is there. The memory of a raw Buffer is
its own bytes (a pooled Buffer.from() shares its ArrayBuffer with other
Buffers); the memory of a ctypes instance is its whole allocation, so
pointer(arr[0])[2] works for an array of structures, and so does
cast(byref(a, 8), POINTER(c_int32))[-1]. An instance that you create with
from_buffer() over a subview (T.from_buffer(buf.subarray(4, 8))) is
bounded by that subview, not by buf. Pointers from an
address (cast(addr, POINTER(T)), a restype, a field) are not checked.pointer() of a function pointer points to a copy of its address:
pointer(f) returns an LP_CFunctionType whose slot holds f's address,
so pf[0]() and pf.contents() call f, but writing pf[0] = g or
pf.contents = g does not retarget f itself, as it does in CPython.
pointer() of a library function (lib.name, lib.func(...)) throws
TypeError; wrap its address first: pointer(CFUNCTYPE(...)(addr)).p.contents = value with a plain value (p.contents = 5 for a scalar
pointee, a plain object for a structure) writes through the pointer, where
CPython raises TypeError. A ctypes instance re-points the pointer, as in
CPython.c_float,
c_int8, c_char, … instance passed beyond argtypes is passed as
double / int, where Python fails on Linux and macOS
(ffi_prep_cif_var failed) and passes them with their own type on Windows. A
VARIANT_BOOL(true) there is the int -1 (its stored short).c_int64, c_uint64,
c_size_t, c_ssize_t) also accept a Buffer or ArrayBuffer, passed as
its address. CPython raises TypeError.memmove() / memset() stop at the end of JS memory (Buffer, typed
array, ArrayBuffer) instead of writing past it.T.from_address(0) throws TypeError from_address: NULL address,
where CPython creates an instance at address 0.get_last_error() / set_last_error() exist on every platform
(Python: Windows only), so the same code runs everywhere. GetLastError()
and SetLastError() are Windows-only, as in CPython.vars(s) is empty): Object.keys(s) and { ...s } do
not list them; use s.toObject(). JSON.stringify(s) and
console.log(s) show the fields.threadSafeCallback. The callback runs on the JavaScript thread, which
is blocked in the synchronous call: the two threads wait for each other
until the native wait times out, or forever (CPython releases the GIL
during the call, so the callback runs). Wait with callAsync() or
callOn() instead, for example
await WaitForSingleObject.callAsync(thread, INFINITE). See
Callbacks.Number.MAX_SAFE_INTEGER (2**53 - 1),
where CPython's limit is Py_ssize_t: a larger _length_ of an Array
subclass throws RangeError The '_length_' attribute is too large, and
a larger array type RangeError array too large.static _fields_ and the _type_ / _length_ of an Array subclass are
validated (and the class finalized) at the first instantiation, sizeof(),
from_buffer() or use as a field type, where CPython raises in the class
statement. An assignment S._fields_ = [...] makes the class final at
once, but its entries are checked at first use too; the field types are
not finalized by it. So after First._fields_ = [["second", Second]],
Second._fields_ = [["first", First]] is accepted and the first use
throws AttributeError Structure or union cannot contain itself, where
CPython rejects the second assignment (_fields_ is final).resize() moves the instance to new memory: pointers, byref() and
memoryview_at() views taken before keep referring to the old memory (in
CPython they dangle too, after the realloc).
create_string_buffer() / create_unicode_buffer() Buffers cannot be
resized (RangeError), where CPython resizes them.memoryview_at() returns a Buffer, or a Proxy of one for a read-only
view (writes and mutating methods throw TypeError
cannot modify read-only memory, .buffer is undefined) and, without
external buffers, for a view of native memory (re-read before reads and
written back after writes). It is not a memoryview: Buffer.from(view)
copies it, view.readonly tells the kind. A NULL address with a non-zero
size throws RangeError NULL pointer access, where CPython returns a
view that crashes when it is read.argtypes fails when it is created
(_argtypes_ has too many arguments (1025), maximum is 1024: this is the
1025th), where CPython fails when it is called.These have no CPython counterpart:
struct() / union() / defineStruct() / defineUnion() and array()
definitions, beside the Python-like classes. Their instances' _buffer is
a view (a Buffer subclass) of the memory they use, not the Buffer
passed to create() or from_buffer()."int32") in the low-level API; use the type
classes such as c_int32 for the Python-compatible API.callAsync(), callOn() and Executor (Asynchronous calls),
threadSafeCallback(), CDLL.func(), close() and using.POINTER(T).create() (also create(address)), fromBuffer(), fromAddress(), .set(),
.address, .isNull; pointer(buffer) is a POINTER(c_void_p) to the
Buffer's memory. fromBuffer(buf) / fromAddress(addr) point to that
memory, while CPython's POINTER(T).from_buffer() / from_address() /
in_dll() (also available) read the pointer stored there.DataView and ArrayBuffer as pointer arguments.
callAsync() and callOn() pass that memory in place, as synchronous
calls: do not detach, resize or modify it until the call settles
(Pointers and memory).2.0 follows Python ctypes more closely. Code relying on the 1.x behavior needs these changes:
| 1.x | 2.0 (as Python) |
|---|---|
ptr.contents returned the value |
returns a live instance: ptr.contents.value (simple types), ptr.contents.x (structs); ptr[0] still returns the value |
POINTER(T) restype returned a bigint address |
returns a pointer object (null for NULL); use .address for the number |
NULL POINTER struct fields were pointer objects |
they are null |
c_char values were numbers |
1-character strings; c_char * n fields read/write as strings |
invalid c_char values were truncated |
TypeError ("one character bytes, bytearray, or an integer in range(256) expected, not ...") |
wrong argument types raised TypeError |
raise ArgumentError (a TypeError subclass), message "argument N: TypeError: ..." |
| unsupported pointer arguments (functions, plain objects) passed NULL | raise ArgumentError ("'function' object cannot be interpreted as ctypes.c_void_p") |
functions without restype / argtypes |
default restype is c_int; without argtypes the call uses the fixed-argument ABI |
create_string_buffer(init) |
also takes size and returns a Buffer with .value / .raw |
c_long / c_ulong (and BOOL, LONG, DWORD, ULONG) fields and .value were numbers on Windows |
BigInt on every platform, like function results; writes accept numbers and BigInt |
wintypes.CHAR was c_ubyte; LPDWORD, PDWORD, LPBYTE, PBYTE, PHKEY were c_void_p |
as Python: CHAR = c_char and pointer types are POINTER(T) (fields and results are pointer objects) |
string_at(addr, n) / wstring_at(addr, n) stopped at the first NUL |
read exactly n units; without n, wstring_at reads up to the NUL (no 256-character limit) |