node-ctypes 1.14.0 → 2.1.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.
@@ -176,6 +192,17 @@ with the `using` declaration for scope-bound cleanup (also on `throw`):
176
192
  Set `NODE_CTYPES_DEBUG_CALLBACKS=1` to log a stack trace for every
177
193
  callback garbage-collected without `.release()`.
178
194
 
195
+ Callbacks invoked by native threads need `threadSafeCallback()`: the
196
+ JavaScript function runs on the main thread, and the calling thread waits
197
+ for its result. Like a timer, a thread-safe callback keeps the event loop
198
+ alive until released; `.unref()` lets the process exit when nothing else
199
+ is pending (calls are still delivered while it runs), `.ref()` restores it:
200
+
201
+ ```javascript
202
+ const onEvent = threadSafeCallback((code) => console.log("event", code), null, [c_int]).unref();
203
+ startWorker(onEvent); // a native library calling onEvent from its own thread
204
+ ```
205
+
179
206
  ### Errors: `errno` and `GetLastError`
180
207
 
181
208
  `GetLastError()` / `get_errno()` read a **private thread-local slot** —
@@ -198,13 +225,15 @@ error instead, call `GetLastError` via FFI like any other function.
198
225
 
199
226
  ### Windows API
200
227
 
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.
228
+ `wintypes` is Python's `ctypes.wintypes`: the same types (BOOL, BYTE,
229
+ WORD, DWORD, HANDLE, HWND, LPARAM, WPARAM, LPCWSTR, …), structures (`RECT`,
230
+ `POINT`, `SIZE`, `MSG`, `FILETIME`, `WIN32_FIND_DATAW`, …) and pointer types
231
+ (`LPDWORD = POINTER(DWORD)`, `LPRECT`, `PHANDLE`, …), plus common extras
232
+ (`LRESULT`, `UINT_PTR`, `LSTATUS`, …).
204
233
 
205
234
  ```javascript
206
- import { WinDLL, Structure, wintypes } from "node-ctypes";
207
- const { WORD, HWND, BOOL, LPVOID } = wintypes;
235
+ import { WinDLL, Structure, POINTER, byref, wintypes } from "node-ctypes";
236
+ const { WORD, HWND, BOOL, RECT, LPRECT } = wintypes;
208
237
 
209
238
  const kernel32 = new WinDLL("kernel32.dll");
210
239
 
@@ -215,12 +244,17 @@ class SYSTEMTIME extends Structure {
215
244
  ];
216
245
  }
217
246
 
218
- const GetLocalTime = kernel32.func("GetLocalTime", null, [LPVOID]);
247
+ kernel32.GetLocalTime.argtypes = [POINTER(SYSTEMTIME)];
248
+ kernel32.GetLocalTime.restype = null;
219
249
  const st = new SYSTEMTIME();
220
- GetLocalTime(st);
250
+ kernel32.GetLocalTime(byref(st));
221
251
 
222
252
  const user32 = new WinDLL("user32.dll");
223
- const IsWindow = user32.func("IsWindow", BOOL, [HWND]);
253
+ user32.GetClientRect.argtypes = [HWND, LPRECT];
254
+ user32.GetClientRect.restype = BOOL;
255
+ const rect = new RECT();
256
+ user32.GetClientRect(hwnd, byref(rect));
257
+ rect.right - rect.left; // LONG (c_long) values are BigInt
224
258
  ```
225
259
 
226
260
  ### Output parameters (`paramflags`)
@@ -304,7 +338,9 @@ const strlen = libc.func("strlen", c_int64, [c_char_p] as const);
304
338
  const n: bigint = strlen("hello"); // typed as bigint, not any
305
339
  ```
306
340
 
307
- For typed struct fields use `defineStruct` instead of `extends Structure`:
341
+ `static _fields_ = [["x", c_int32]]` compiles as written in Python (no
342
+ `as const`). For typed struct fields use `defineStruct` instead of
343
+ `extends Structure`:
308
344
 
309
345
  ```ts
310
346
  class Point extends defineStruct({ x: c_int32, y: c_int32 }) {
@@ -313,6 +349,17 @@ class Point extends defineStruct({ x: c_int32, y: c_int32 }) {
313
349
  const p = new Point({ x: 3, y: 4 }); // p.x, p.y typed as number
314
350
  ```
315
351
 
352
+ `struct()` / `union()` fields, `POINTER()` targets and arrays of numeric
353
+ types are typed too; a `null` return type is `void`:
354
+
355
+ ```ts
356
+ const PointDef = struct({ x: c_int32, y: c_double });
357
+ PointDef.get(buf, "y"); // number
358
+ POINTER(c_int32).fromAddress(addr)[0]; // number (.contents: c_int32 instance)
359
+ array(c_int32, 4).create([1, 2, 3, 4])[0]; // number
360
+ libc.func("srand", null, [c_uint32]); // returns undefined
361
+ ```
362
+
316
363
  ---
317
364
 
318
365
  ## API reference
@@ -329,38 +376,40 @@ const p = new Point({ x: 3, y: 4 }); // p.x, p.y typed as number
329
376
  | `c_uint32` | `c_uint` | 4 | |
330
377
  | `c_int64` | `c_longlong` | 8 | |
331
378
  | `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` |
379
+ | `c_long` | | platform | 4 on Windows, 8 on Unix 64-bit; BigInt values |
380
+ | `c_ulong` | | platform | mirrors `c_long`; BigInt values |
334
381
  | `c_float` | | 4 | |
335
382
  | `c_double` | | 8 | |
336
383
  | `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 |
384
+ | `c_char` | | 1 | 1-char string (Python `bytes`); also 0..255 |
385
+ | `c_wchar` | | 2 or 4 | 1-char string; 2 on Windows, 4 on Unix |
339
386
  | `c_char_p` | | pointer | `char *` (NUL-terminated) |
340
387
  | `c_wchar_p` | | pointer | `wchar_t *` (NUL-terminated wide) |
341
- | `c_void_p` | | pointer | opaque pointer / `HANDLE` |
388
+ | `c_void_p` | `c_voidp` | pointer | opaque pointer / `HANDLE` |
389
+ | `c_time_t` | | 8 | `time_t` (`SIZEOF_TIME_T`) |
342
390
  | `c_size_t` | | pointer | pointer-sized unsigned integer |
343
391
  | `c_ssize_t` | | pointer | pointer-sized signed integer |
344
392
  | `HRESULT` | | 4 | `c_int32` subclass — auto-raise on `OleDLL` |
345
393
 
346
- Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
394
+ Plus the Win32 types, structures and pointer types of `ctypes.wintypes` under `wintypes`.
347
395
 
348
396
  ### Library loaders
349
397
 
350
- - `CDLL(name, { use_errno?, use_last_error? })` — C calling convention
398
+ - `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
399
  - `WinDLL(name, ...)` — Windows `__stdcall`
352
400
  - `OleDLL(name, ...)` — like `WinDLL`, auto-raises on negative `HRESULT`
353
401
  - `find_library(name)` — cross-platform name resolution
354
- - `cdll.<libname>`, `windll.<libname>` — lazy namespaces
402
+ - `cdll.<libname>`, `windll.<libname>` — lazy namespaces; `cdll.LoadLibrary(name)`, `new LibraryLoader(CDLL)`
403
+ - Functions without `restype` return `c_int`; without `argtypes` the arguments are converted from their JS values (as Python)
355
404
 
356
405
  ### Type constructors
357
406
 
358
407
  - `struct({...})` / `class extends Structure` — composite struct types
359
408
  - `class extends Union` — union types
360
- - `array(type, n)` — Python's `type * n`
409
+ - `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
410
  - `POINTER(type)` — pointer-to-type; accepts a thunk `POINTER(() => T)`
362
411
  - `pointer(instance)` — pointer to an existing c-data instance
363
- - `CFUNCTYPE(restype, ...argtypes)` — callback type
412
+ - `CFUNCTYPE(restype, ...argtypes)` — function pointer type: `proto(jsFn)` (callback), `proto(address)`, `proto([name, lib], paramflags?)` (Python: `proto((name, dll), paramflags)`)
364
413
  - `WINFUNCTYPE(restype, ...argtypes)` — `__stdcall` callback type
365
414
  - `defineStruct({...})` — typed-TS variant of `struct`
366
415
 
@@ -370,15 +419,16 @@ Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
370
419
  - `addressof(obj)` → BigInt
371
420
  - `byref(obj)` — lightweight pass-by-reference marker
372
421
  - `cast(ptr, type)` — reinterpret a pointer as another type
373
- - `memmove(dst, src, n)` / `memset(dst, val, n)`
422
+ - `memmove(dst, src, n)` / `memset(dst, val, n)` — buffers, ctypes instances, pointers or addresses
374
423
  - `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?)`
424
+ - `create_string_buffer(init, size?)` / `c_buffer` / `create_unicode_buffer(init, size?)` — with `.value` (and `.raw`)
425
+ - `string_at(addr, size?)` / `wstring_at(addr, size?)` — exactly `size` units, or up to the NUL
377
426
 
378
427
  ### Error slots
379
428
 
380
429
  - `get_errno()` / `set_errno(v)`
381
- - `GetLastError()` / `SetLastError(v)` / `FormatError(code)`
430
+ - `GetLastError()` / `SetLastError(v)` / `FormatError(code)`, Python names `get_last_error()` / `set_last_error(v)` (all platforms)
431
+ - `ArgumentError` — raised for arguments that do not match `argtypes` (`"argument N: TypeError: ..."`)
382
432
  - Per-library: `lib.get_last_error()` / `lib.get_errno()`
383
433
 
384
434
  ### Structure helpers
@@ -396,12 +446,14 @@ Plus Win32 aliases under `wintypes` (full `ctypes.wintypes` parity).
396
446
  ### What works identically
397
447
 
398
448
  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`.
449
+ arrays (also of arrays, pointers and function pointers), pointers and
450
+ pointer arithmetic (also `POINTER(POINTER(T))`), callbacks (`CFUNCTYPE` /
451
+ `WINFUNCTYPE`, also as struct fields), `prototype((name, dll), paramflags)`,
452
+ `from_buffer` / `from_buffer_copy` / `from_address` / `in_dll`,
453
+ `_as_parameter_` / `from_param`, `paramflags` out-params, `errcheck`,
454
+ `use_errno` / `use_last_error`, `OleDLL` + `HRESULT` auto-raise,
455
+ `BigEndianStructure` / `LittleEndianStructure` and union variants,
456
+ `ctypes.wintypes`, keepalive of objects assigned to fields (`_objects`).
405
457
 
406
458
  ### Differences
407
459
 
@@ -412,9 +464,18 @@ variants, all Win32 aliases under `wintypes`.
412
464
  (Python-like) and `struct({...})` (functional) are both supported.
413
465
  - **Only type classes**, not string literals: `c_int32`, never `"int32"`
414
466
  — same as Python.
467
+ - **`bytes` are JS strings**: `c_char` values, `c_char * n` arrays and
468
+ fields, `c_char_p` and `create_string_buffer().value` use strings (UTF-8)
469
+ where Python uses `bytes`; `.raw` is a `Buffer`.
470
+ - **NULL pointers are `null`**, where Python returns a falsy pointer object.
415
471
  - **`c_char_p` / `c_wchar_p` accept raw addresses** (BigInt/number) as
416
472
  argtypes. Python is stricter (raises `TypeError` on `int`). For
417
473
  portable code use `c_void_p` there; both libraries accept it.
474
+ - **`get_last_error()` / `set_last_error()`** exist on every platform
475
+ (Python: Windows only), so the same code runs everywhere.
476
+ - **64-bit and pointer-sized integers** (`c_int64`, `c_uint64`,
477
+ `c_size_t`, `c_ssize_t`) also accept `null` (as 0) and a `Buffer`
478
+ (as its address).
418
479
 
419
480
  ### Not supported
420
481
 
@@ -425,17 +486,40 @@ variants, all Win32 aliases under `wintypes`.
425
486
  - **`c_longdouble`** (80/128-bit float, `ffi_type_longdouble`) — rarely
426
487
  used; fall back to `c_double` or raw bytes.
427
488
 
489
+ ### Migrating from 1.x
490
+
491
+ 2.0 follows Python ctypes more closely. Code relying on the 1.x behavior
492
+ needs these changes:
493
+
494
+ | 1.x | 2.0 (as Python) |
495
+ | --- | --- |
496
+ | `ptr.contents` returned the value | returns a live instance: `ptr.contents.value` (simple types), `ptr.contents.x` (structs); `ptr[0]` still returns the value |
497
+ | `POINTER(T)` restype returned a `bigint` address | returns a pointer object (`null` for NULL); use `.address` for the number |
498
+ | NULL `POINTER` struct fields were pointer objects | they are `null` |
499
+ | `c_char` values were numbers | 1-character strings; `c_char * n` fields read/write as strings |
500
+ | invalid `c_char` values were truncated | `TypeError` (`"one character bytes, bytearray or integer expected"`) |
501
+ | wrong argument types raised `TypeError` | raise `ArgumentError` (a `TypeError` subclass), message `"argument N: TypeError: ..."` |
502
+ | unsupported pointer arguments (functions, plain objects) passed NULL | raise `ArgumentError` (`"wrong type"`) |
503
+ | functions without `restype` / `argtypes` | default `restype` is `c_int`; without `argtypes` the call uses the fixed-argument ABI |
504
+ | `create_string_buffer(init)` | also takes `size` and returns a Buffer with `.value` / `.raw` |
505
+ | `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 |
506
+ | `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) |
507
+ | `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) |
508
+
428
509
  ---
429
510
 
430
511
  ## Examples
431
512
 
432
- - [Windows Controls Demo](examples/windows/demo_controls.js) — Win32 common controls
433
- - [Windows Registry Demo](examples/windows/demo_registry.js) — `setValue` / `getValue` / `openKey` / `deleteKey`
434
- - [Windows Tray Demo](examples/windows/demo_tray.js) — system tray icon + popup menu
435
- - [Windows COM (Shortcut)](examples/windows/demo_comtypes_file.js) — `IShellLinkW` + `IPersistFile`
436
- - [Windows COM (Active Directory)](examples/windows/demo_comtypes_ads.js) — `IDirectorySearch` / `ADsOpenObject`
437
- - [Windows LDAP Demo](examples/windows/demo_ldap.js) — LDAPv3 paged search (`wldap32`)
438
- - [Smart Card (PC/SC) Demo](examples/demo_scard.js) — `WinSCard` on Windows, `pcsclite` on macOS/Linux
513
+ Each example in `examples/` has its own README; see the [index](examples/README.md).
514
+
515
+ - [Embedded Python](examples/cross-platform/python/README.md) — CPython through its C API: code, modules, callbacks, JavaScript objects by reference, shared memory, threads, asyncio and cancellation (Windows, macOS, Linux)
516
+ - [Smart card (PC/SC)](examples/cross-platform/smartcard/README.md) — `winscard` on Windows, `PCSC.framework` on macOS, `libpcsclite` on Linux
517
+ - [Accessibility](examples/macos/accessibility/README.md) — macOS UI automation with the Accessibility API
518
+ - [COM automation](examples/windows/com/README.md) — shell shortcuts (`IShellLinkW`) and Active Directory (`IDirectorySearch`)
519
+ - [Controls](examples/windows/controls/README.md) — Win32 common controls
520
+ - [LDAP](examples/windows/ldap/README.md) — LDAPv3 paged search (`wldap32`)
521
+ - [Registry](examples/windows/registry/README.md) — `setValue` / `getValue` / `openKey` / `deleteKey`
522
+ - [System tray](examples/windows/tray/README.md) — tray icon + popup menu
439
523
 
440
524
  ---
441
525
 
@@ -443,6 +527,7 @@ variants, all Win32 aliases under `wintypes`.
443
527
 
444
528
  ```bash
445
529
  cd tests && npm install && npm run test # unit tests (JS + Python parity)
530
+ npm run test:types # type-check lib/index.d.ts (tests/types)
446
531
  npm run docs # TypeDoc API site in docs/
447
532
  npm run docs:serve # preview
448
533
  ```
Binary file
Binary file