node-ctypes 1.13.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,8 @@ If you know Python ctypes, you already know node-ctypes.
17
17
  npm install node-ctypes
18
18
  ```
19
19
 
20
- Prebuilt binaries ship for Windows, Linux, and macOS (x64/ARM64).
20
+ Prebuilt binaries ship for Windows, macOS 13.5+ and Linux (glibc 2.28+ or musl /
21
+ Alpine), on x64 and ARM64 — wherever Node 24 runs.
21
22
 
22
23
  ```javascript
23
24
  import { CDLL, Structure, c_int32, c_char_p } from "node-ctypes";
@@ -78,7 +79,7 @@ auto-`HRESULT`-checking use `OleDLL`.
78
79
  ### Structs, unions, bit fields, arrays
79
80
 
80
81
  ```javascript
81
- import { Structure, Union, array, c_int32, c_uint32, c_float } from "node-ctypes";
82
+ import { Structure, Union, array, c_int32, c_uint32, c_float, c_char } from "node-ctypes";
82
83
 
83
84
  class Rect extends Structure {
84
85
  static _fields_ = [
@@ -107,7 +108,11 @@ class Flags extends Structure {
107
108
 
108
109
  // Arrays: elementType * count (Python: `c_int32 * 5`)
109
110
  const IntArr5 = array(c_int32, 5);
110
- const buf = IntArr5.create([1, 2, 3, 4, 5]);
111
+ const arr = IntArr5(1, 2, 3, 4, 5); // Python: (c_int32 * 5)(1, 2, 3, 4, 5)
112
+
113
+ // char arrays read and write as strings (Python: bytes)
114
+ const name = array(c_char, 16)();
115
+ name.value = "node"; // .value / .raw as in Python
111
116
  ```
112
117
 
113
118
  Nested structs, anonymous fields (`static _anonymous_ = ["data"]`),
@@ -122,10 +127,10 @@ import { POINTER, pointer, cast, c_int32, c_void_p } from "node-ctypes";
122
127
  // Pointer to an existing c-data instance (Python: pointer(x))
123
128
  const x = new c_int32(42);
124
129
  const px = pointer(x);
125
- px.contents; // 42 (Python: *px or px.contents)
126
- px[0]; // 42 (Python: px[0])
130
+ px.contents.value; // 42 (Python: px.contents.value — a live c_int32)
131
+ px[0]; // 42 (Python: px[0])
127
132
  px[0] = 100;
128
- x.value; // 100 (same memory)
133
+ x.value; // 100 (same memory)
129
134
 
130
135
  // View existing memory as a typed pointer
131
136
  const IntPtr = POINTER(c_int32);
@@ -137,8 +142,14 @@ const q = cast(someBuffer, POINTER(c_int32));
137
142
  const r = cast(addressAsBigInt, POINTER(MyStruct));
138
143
  ```
139
144
 
145
+ A `POINTER(T)` restype returns a pointer object, and a NULL pointer (return
146
+ value or struct field) is `null` — where Python returns a falsy pointer.
147
+
140
148
  To hand a raw address to a function, use `c_void_p` as the argtype for
141
- portable code (Python accepts raw `int` only there).
149
+ portable code (Python accepts raw `int` only there). As in Python, values
150
+ that cannot be converted (a plain JS function, an object) raise
151
+ `ArgumentError` instead of passing NULL; `c_void_p` also accepts strings
152
+ (as `char *`, Python `bytes`) and any TypedArray/ArrayBuffer.
142
153
 
143
154
  ### Callbacks
144
155
 
@@ -156,6 +167,11 @@ const cmp2 = callback(
156
167
  [c_void_p, c_void_p]
157
168
  );
158
169
 
170
+ // Pass the callback itself (as in Python) or its address `cmp.pointer`.
171
+ qsort(arr, 5, 4, cmp);
172
+
173
+ // CFUNCTYPE types also work as struct fields (read back as a callable).
174
+
159
175
  // IMPORTANT: release the trampoline when done. Unlike Python, we cannot
160
176
  // rely on GC — the callback holds a libffi closure that native code may
161
177
  // still reference.
@@ -198,13 +214,15 @@ error instead, call `GetLastError` via FFI like any other function.
198
214
 
199
215
  ### Windows API
200
216
 
201
- `wintypes` mirrors `ctypes.wintypes` (BOOL, BYTE, WORD, DWORD, HANDLE,
202
- HWND, LPARAM, WPARAM, LRESULT, LPCWSTR, LPSTR, HGDIOBJ, …) — pure
203
- aliases of the primitive CTypes, so signatures read identical to MSDN.
217
+ `wintypes` is Python's `ctypes.wintypes`: the same types (BOOL, BYTE,
218
+ WORD, DWORD, HANDLE, HWND, LPARAM, WPARAM, LPCWSTR, …), structures (`RECT`,
219
+ `POINT`, `SIZE`, `MSG`, `FILETIME`, `WIN32_FIND_DATAW`, …) and pointer types
220
+ (`LPDWORD = POINTER(DWORD)`, `LPRECT`, `PHANDLE`, …), plus common extras
221
+ (`LRESULT`, `UINT_PTR`, `LSTATUS`, …).
204
222
 
205
223
  ```javascript
206
- import { WinDLL, Structure, wintypes } from "node-ctypes";
207
- const { WORD, HWND, BOOL, LPVOID } = wintypes;
224
+ import { WinDLL, Structure, POINTER, byref, wintypes } from "node-ctypes";
225
+ const { WORD, HWND, BOOL, RECT, LPRECT } = wintypes;
208
226
 
209
227
  const kernel32 = new WinDLL("kernel32.dll");
210
228
 
@@ -215,12 +233,17 @@ class SYSTEMTIME extends Structure {
215
233
  ];
216
234
  }
217
235
 
218
- const GetLocalTime = kernel32.func("GetLocalTime", null, [LPVOID]);
236
+ kernel32.GetLocalTime.argtypes = [POINTER(SYSTEMTIME)];
237
+ kernel32.GetLocalTime.restype = null;
219
238
  const st = new SYSTEMTIME();
220
- GetLocalTime(st);
239
+ kernel32.GetLocalTime(byref(st));
221
240
 
222
241
  const user32 = new WinDLL("user32.dll");
223
- const IsWindow = user32.func("IsWindow", BOOL, [HWND]);
242
+ user32.GetClientRect.argtypes = [HWND, LPRECT];
243
+ user32.GetClientRect.restype = BOOL;
244
+ const rect = new RECT();
245
+ user32.GetClientRect(hwnd, byref(rect));
246
+ rect.right - rect.left; // LONG (c_long) values are BigInt
224
247
  ```
225
248
 
226
249
  ### Output parameters (`paramflags`)
@@ -304,7 +327,9 @@ const strlen = libc.func("strlen", c_int64, [c_char_p] as const);
304
327
  const n: bigint = strlen("hello"); // typed as bigint, not any
305
328
  ```
306
329
 
307
- For typed struct fields use `defineStruct` instead of `extends Structure`:
330
+ `static _fields_ = [["x", c_int32]]` compiles as written in Python (no
331
+ `as const`). For typed struct fields use `defineStruct` instead of
332
+ `extends Structure`:
308
333
 
309
334
  ```ts
310
335
  class Point extends defineStruct({ x: c_int32, y: c_int32 }) {
@@ -313,6 +338,17 @@ class Point extends defineStruct({ x: c_int32, y: c_int32 }) {
313
338
  const p = new Point({ x: 3, y: 4 }); // p.x, p.y typed as number
314
339
  ```
315
340
 
341
+ `struct()` / `union()` fields, `POINTER()` targets and arrays of numeric
342
+ types are typed too; a `null` return type is `void`:
343
+
344
+ ```ts
345
+ const PointDef = struct({ x: c_int32, y: c_double });
346
+ PointDef.get(buf, "y"); // number
347
+ POINTER(c_int32).fromAddress(addr)[0]; // number (.contents: c_int32 instance)
348
+ array(c_int32, 4).create([1, 2, 3, 4])[0]; // number
349
+ libc.func("srand", null, [c_uint32]); // returns undefined
350
+ ```
351
+
316
352
  ---
317
353
 
318
354
  ## API reference
@@ -329,38 +365,40 @@ const p = new Point({ x: 3, y: 4 }); // p.x, p.y typed as number
329
365
  | `c_uint32` | `c_uint` | 4 | |
330
366
  | `c_int64` | `c_longlong` | 8 | |
331
367
  | `c_uint64` | `c_ulonglong` | 8 | |
332
- | `c_long` | | platform | 4 on Windows (LLP64), 8 on Unix 64-bit (LP64) |
333
- | `c_ulong` | | platform | platform-dependent, mirrors `c_long` |
368
+ | `c_long` | | platform | 4 on Windows, 8 on Unix 64-bit; BigInt values |
369
+ | `c_ulong` | | platform | mirrors `c_long`; BigInt values |
334
370
  | `c_float` | | 4 | |
335
371
  | `c_double` | | 8 | |
336
372
  | `c_bool` | | 1 | |
337
- | `c_char` | | 1 | accepts a 1-char string or int |
338
- | `c_wchar` | | 2 or 4 | 2 on Windows (UTF-16), 4 on Unix |
373
+ | `c_char` | | 1 | 1-char string (Python `bytes`); also 0..255 |
374
+ | `c_wchar` | | 2 or 4 | 1-char string; 2 on Windows, 4 on Unix |
339
375
  | `c_char_p` | | pointer | `char *` (NUL-terminated) |
340
376
  | `c_wchar_p` | | pointer | `wchar_t *` (NUL-terminated wide) |
341
- | `c_void_p` | | pointer | opaque pointer / `HANDLE` |
377
+ | `c_void_p` | `c_voidp` | pointer | opaque pointer / `HANDLE` |
378
+ | `c_time_t` | | 8 | `time_t` (`SIZEOF_TIME_T`) |
342
379
  | `c_size_t` | | pointer | pointer-sized unsigned integer |
343
380
  | `c_ssize_t` | | pointer | pointer-sized signed integer |
344
381
  | `HRESULT` | | 4 | `c_int32` subclass — auto-raise on `OleDLL` |
345
382
 
346
- Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
383
+ Plus the Win32 types, structures and pointer types of `ctypes.wintypes` under `wintypes`.
347
384
 
348
385
  ### Library loaders
349
386
 
350
- - `CDLL(name, { use_errno?, use_last_error? })` — C calling convention
387
+ - `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`)
351
388
  - `WinDLL(name, ...)` — Windows `__stdcall`
352
389
  - `OleDLL(name, ...)` — like `WinDLL`, auto-raises on negative `HRESULT`
353
390
  - `find_library(name)` — cross-platform name resolution
354
- - `cdll.<libname>`, `windll.<libname>` — lazy namespaces
391
+ - `cdll.<libname>`, `windll.<libname>` — lazy namespaces; `cdll.LoadLibrary(name)`, `new LibraryLoader(CDLL)`
392
+ - Functions without `restype` return `c_int`; without `argtypes` the arguments are converted from their JS values (as Python)
355
393
 
356
394
  ### Type constructors
357
395
 
358
396
  - `struct({...})` / `class extends Structure` — composite struct types
359
397
  - `class extends Union` — union types
360
- - `array(type, n)` — Python's `type * n`
398
+ - `array(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` types
361
399
  - `POINTER(type)` — pointer-to-type; accepts a thunk `POINTER(() => T)`
362
400
  - `pointer(instance)` — pointer to an existing c-data instance
363
- - `CFUNCTYPE(restype, ...argtypes)` — callback type
401
+ - `CFUNCTYPE(restype, ...argtypes)` — function pointer type: `proto(jsFn)` (callback), `proto(address)`, `proto([name, lib], paramflags?)` (Python: `proto((name, dll), paramflags)`)
364
402
  - `WINFUNCTYPE(restype, ...argtypes)` — `__stdcall` callback type
365
403
  - `defineStruct({...})` — typed-TS variant of `struct`
366
404
 
@@ -370,15 +408,16 @@ Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
370
408
  - `addressof(obj)` → BigInt
371
409
  - `byref(obj)` — lightweight pass-by-reference marker
372
410
  - `cast(ptr, type)` — reinterpret a pointer as another type
373
- - `memmove(dst, src, n)` / `memset(dst, val, n)`
411
+ - `memmove(dst, src, n)` / `memset(dst, val, n)` — buffers, ctypes instances, pointers or addresses
374
412
  - `readValue(ptr, type, offset?)` / `writeValue(ptr, type, val, offset?)`
375
- - `create_string_buffer(init)` / `create_unicode_buffer(init)`
376
- - `string_at(addr, size?)` / `wstring_at(addr, size?)`
413
+ - `create_string_buffer(init, size?)` / `c_buffer` / `create_unicode_buffer(init, size?)` — with `.value` (and `.raw`)
414
+ - `string_at(addr, size?)` / `wstring_at(addr, size?)` — exactly `size` units, or up to the NUL
377
415
 
378
416
  ### Error slots
379
417
 
380
418
  - `get_errno()` / `set_errno(v)`
381
- - `GetLastError()` / `SetLastError(v)` / `FormatError(code)`
419
+ - `GetLastError()` / `SetLastError(v)` / `FormatError(code)`, Python names `get_last_error()` / `set_last_error(v)` (all platforms)
420
+ - `ArgumentError` — raised for arguments that do not match `argtypes` (`"argument N: TypeError: ..."`)
382
421
  - Per-library: `lib.get_last_error()` / `lib.get_errno()`
383
422
 
384
423
  ### Structure helpers
@@ -396,12 +435,14 @@ Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
396
435
  ### What works identically
397
436
 
398
437
  Structs, unions, bit fields, anonymous fields, `_pack_`, nested layouts,
399
- arrays, pointers and pointer arithmetic, callbacks (`CFUNCTYPE` /
400
- `WINFUNCTYPE`), `from_buffer` / `from_buffer_copy` / `from_address` /
401
- `in_dll`, `_as_parameter_` / `from_param`, `paramflags` out-params,
402
- `errcheck`, `use_errno` / `use_last_error`, `OleDLL` + `HRESULT`
403
- auto-raise, `BigEndianStructure` / `LittleEndianStructure` and union
404
- variants, all Win32 aliases under `wintypes`.
438
+ arrays (also of arrays, pointers and function pointers), pointers and
439
+ pointer arithmetic (also `POINTER(POINTER(T))`), callbacks (`CFUNCTYPE` /
440
+ `WINFUNCTYPE`, also as struct fields), `prototype((name, dll), paramflags)`,
441
+ `from_buffer` / `from_buffer_copy` / `from_address` / `in_dll`,
442
+ `_as_parameter_` / `from_param`, `paramflags` out-params, `errcheck`,
443
+ `use_errno` / `use_last_error`, `OleDLL` + `HRESULT` auto-raise,
444
+ `BigEndianStructure` / `LittleEndianStructure` and union variants,
445
+ `ctypes.wintypes`, keepalive of objects assigned to fields (`_objects`).
405
446
 
406
447
  ### Differences
407
448
 
@@ -412,9 +453,18 @@ variants, all Win32 aliases under `wintypes`.
412
453
  (Python-like) and `struct({...})` (functional) are both supported.
413
454
  - **Only type classes**, not string literals: `c_int32`, never `"int32"`
414
455
  — same as Python.
456
+ - **`bytes` are JS strings**: `c_char` values, `c_char * n` arrays and
457
+ fields, `c_char_p` and `create_string_buffer().value` use strings (UTF-8)
458
+ where Python uses `bytes`; `.raw` is a `Buffer`.
459
+ - **NULL pointers are `null`**, where Python returns a falsy pointer object.
415
460
  - **`c_char_p` / `c_wchar_p` accept raw addresses** (BigInt/number) as
416
461
  argtypes. Python is stricter (raises `TypeError` on `int`). For
417
462
  portable code use `c_void_p` there; both libraries accept it.
463
+ - **`get_last_error()` / `set_last_error()`** exist on every platform
464
+ (Python: Windows only), so the same code runs everywhere.
465
+ - **64-bit and pointer-sized integers** (`c_int64`, `c_uint64`,
466
+ `c_size_t`, `c_ssize_t`) also accept `null` (as 0) and a `Buffer`
467
+ (as its address).
418
468
 
419
469
  ### Not supported
420
470
 
@@ -425,6 +475,26 @@ variants, all Win32 aliases under `wintypes`.
425
475
  - **`c_longdouble`** (80/128-bit float, `ffi_type_longdouble`) — rarely
426
476
  used; fall back to `c_double` or raw bytes.
427
477
 
478
+ ### Migrating from 1.x
479
+
480
+ 2.0 follows Python ctypes more closely. Code relying on the 1.x behavior
481
+ needs these changes:
482
+
483
+ | 1.x | 2.0 (as Python) |
484
+ | --- | --- |
485
+ | `ptr.contents` returned the value | returns a live instance: `ptr.contents.value` (simple types), `ptr.contents.x` (structs); `ptr[0]` still returns the value |
486
+ | `POINTER(T)` restype returned a `bigint` address | returns a pointer object (`null` for NULL); use `.address` for the number |
487
+ | NULL `POINTER` struct fields were pointer objects | they are `null` |
488
+ | `c_char` values were numbers | 1-character strings; `c_char * n` fields read/write as strings |
489
+ | invalid `c_char` values were truncated | `TypeError` (`"one character bytes, bytearray or integer expected"`) |
490
+ | wrong argument types raised `TypeError` | raise `ArgumentError` (a `TypeError` subclass), message `"argument N: TypeError: ..."` |
491
+ | unsupported pointer arguments (functions, plain objects) passed NULL | raise `ArgumentError` (`"wrong type"`) |
492
+ | functions without `restype` / `argtypes` | default `restype` is `c_int`; without `argtypes` the call uses the fixed-argument ABI |
493
+ | `create_string_buffer(init)` | also takes `size` and returns a Buffer with `.value` / `.raw` |
494
+ | `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 |
495
+ | `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) |
496
+ | `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) |
497
+
428
498
  ---
429
499
 
430
500
  ## Examples
@@ -443,6 +513,7 @@ variants, all Win32 aliases under `wintypes`.
443
513
 
444
514
  ```bash
445
515
  cd tests && npm install && npm run test # unit tests (JS + Python parity)
516
+ npm run test:types # type-check lib/index.d.ts (tests/types)
446
517
  npm run docs # TypeDoc API site in docs/
447
518
  npm run docs:serve # preview
448
519
  ```
Binary file
Binary file