node-ctypes 2.7.0 → 2.9.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/CHANGELOG.md CHANGED
@@ -7,6 +7,85 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.9.0] - 2026-11-05
11
+
12
+ ### Added
13
+
14
+ - **Backend-independent ABI regressions**: compiled C callers verify scalar
15
+ aliases, narrow GP/FP stack arguments, small/large aggregates and homogeneous
16
+ float/double aggregates for sync/async calls and ordinary/thread-safe callbacks.
17
+ Include Darwin stack-slot coverage and a safe indirect-pointer alignment probe.
18
+ - **Koffi C-loop callback comparison**: check 64 consecutive i32 callbacks per
19
+ native call with the same C fixture, reporting batch latency separately from
20
+ the single-callback workload and normalizing both int64 results to Number.
21
+ - **node:ffi benchmark coverage**: expand to 25 workloads with narrow scalars,
22
+ GP/FP stack arguments, C-loop/host-thread-safe callbacks and inferred calls.
23
+ Document numeric bool normalization and explicitly typed inference counterparts;
24
+ unsupported aggregate, variadic and async APIs remain not compared.
25
+
26
+ ### Changed
27
+
28
+ - **Native backend source boundaries**: keep `src` flat and isolate
29
+ `libffi_types`, `libffi_call` and `libffi_callback`, with concrete RAII-managed
30
+ state and lazy descriptor caches. Common wrappers retain Node-API marshalling,
31
+ selection and sync/async/TSFN ownership. Scalar/direct headers no longer depend
32
+ on libffi; return-word compatibility is checked at compile time. CMake discovers
33
+ native sources with `GLOB_RECURSE` and `CONFIGURE_DEPENDS`.
34
+ - **libffi upstream alignment**: temporarily pin the unmodified submodule to
35
+ `d02afc25e8ea3aac9e78e227748e1fd7c9f14c82` for the Darwin small-composite
36
+ stack-slot fixes and regenerate integration headers, pending an official tag.
37
+ The indirect-pointer alignment defect remains tracked in
38
+ [libffi/libffi#1057](https://github.com/libffi/libffi/issues/1057), without a local vendor patch.
39
+ - **Fixed sync/async preparation**: select direct invokers from finalized native
40
+ metadata before preparing libffi types, CIFs or call plans; fixed workers reuse
41
+ that selection and pin the parent function and library. Unsupported signatures
42
+ retain eager libffi setup. Extra calls use cached sync or worker-owned async
43
+ CIFs, prepared on the JavaScript thread without changing the fixed invoker.
44
+
45
+ ### Performance
46
+
47
+ - **Inferred and variadic arguments**: bypass object conversion for primitive
48
+ JavaScript extras and keep type/value metadata for up to 16 extras on the stack.
49
+ Generic sync calls fuse inference/storage for leading numeric extras within
50
+ 16 total arguments. Preserve the eight-argument simple path, conversion order,
51
+ scalar snapshots and ownership, with boundary, promotion, wide/non-finite
52
+ number and reentrant-cache regressions.
53
+ - **Owned callback snapshots**: reuse the existing aligned JavaScript buffer
54
+ pool for eligible high-level arguments, with independent, never-recycled
55
+ slices; raw native and over-aligned arguments retain Node-API copies.
56
+ Cache standard handlers and readers, not individual views, while respecting
57
+ custom definition getters and mirrored synchronization.
58
+
59
+ ### Known limitations
60
+
61
+ - **Darwin ARM64 indirect arguments**: libffi can misalign a large aggregate's
62
+ indirect pointer after a narrow stack scalar. Temporarily skip the stack-tag
63
+ regression only on Darwin ARM64 until an upstream fix is available.
64
+ - **Windows ARM64 variadic HFAs**: a named four-double HFA argument (32 bytes)
65
+ crashes in upstream libffi. Temporarily skip its regression only on Windows
66
+ ARM64, retaining coverage on other targets.
67
+ This is not a runtime fix.
68
+
69
+ ## [2.8.0] - 2026-11-04
70
+
71
+ ### Fixed
72
+
73
+ - **Scalar argument marshalling**: read genuine non-pointer CData arguments from
74
+ their backing bytes instead of overridden `.value` getters. Snapshot each
75
+ scalar before converting later arguments, including calls without `argtypes`,
76
+ matching CPython's conversion order.
77
+ - **Scalar adapters**: accept `from_param` results whose native scalar kind
78
+ matches the declared type, even when the CData instance belongs to a different
79
+ JavaScript class.
80
+ - **Examples navigation**: use explicit Electron and Cryptoki page titles
81
+ instead of duplicate `README` labels in the generated documentation.
82
+
83
+ ### Performance
84
+
85
+ - **Cached library symbols**: reuse attribute-function wrappers with a single
86
+ cache lookup instead of separate `Map.has()` and `Map.get()` calls, preserving
87
+ wrapper identity, signature changes and lazy symbol resolution.
88
+
10
89
  ## [2.7.0] - 2026-11-03
11
90
 
12
91
  ### Changed
@@ -1051,7 +1130,9 @@ It contains breaking changes: see [Migrating from 1.x](README.md#migrating-from-
1051
1130
 
1052
1131
  Initial releases.
1053
1132
 
1054
- [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.7.0...HEAD
1133
+ [Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.9.0...HEAD
1134
+ [2.9.0]: https://github.com/dmazzella/node-ctypes/compare/v2.8.0...v2.9.0
1135
+ [2.8.0]: https://github.com/dmazzella/node-ctypes/compare/v2.7.0...v2.8.0
1055
1136
  [2.7.0]: https://github.com/dmazzella/node-ctypes/compare/v2.6.0...v2.7.0
1056
1137
  [2.6.0]: https://github.com/dmazzella/node-ctypes/compare/v2.5.0...v2.6.0
1057
1138
  [2.5.0]: https://github.com/dmazzella/node-ctypes/compare/v2.4.0...v2.5.0
package/README.md CHANGED
@@ -36,7 +36,9 @@ import { CDLL, Structure, c_int32, c_size_t, c_char_p } from "node-ctypes";
36
36
  const libc = new CDLL(process.platform === "win32" ? "msvcrt" : null);
37
37
 
38
38
  // 2. Declare a function signature
39
- const strlen = libc.func("strlen", c_size_t, [c_char_p]);
39
+ const strlen = libc.strlen;
40
+ strlen.argtypes = [c_char_p];
41
+ strlen.restype = c_size_t;
40
42
  console.log(strlen("hello")); // 5n
41
43
 
42
44
  // 3. Declare a struct
@@ -88,10 +90,16 @@ auto-`HRESULT`-checking use `OleDLL`.
88
90
 
89
91
  Direct native calls are limited to a bounded set of exact scalar C++
90
92
  signatures with up to four arguments, on 64-bit little-endian targets using
91
- the default ABI. Other signatures use the existing cached libffi plans/CIFs,
93
+ the default ABI. By default, other signatures use the existing cached libffi plans/CIFs,
92
94
  including pointers and strings whose pointee types and qualifiers are not
93
95
  encoded in the native type metadata. Float/double arguments continue to use
94
96
  libffi on x86-64. This changes the optimization route, not the JavaScript API.
97
+ Eligible fixed invokers are selected before constructing libffi types, CIFs or
98
+ call plans. Fixed async workers reuse the same selected invoker, with their own
99
+ argument/result storage. Other signatures retain eager fallback setup;
100
+ additional arguments bypass fixed invokers and prepare their libffi metadata
101
+ on the JavaScript thread. Inferred calls use the ordinary ABI; true variadic
102
+ calls preserve the declared named-prefix boundary.
95
103
 
96
104
  ### Structs, unions, bit fields, arrays
97
105
 
@@ -269,7 +277,7 @@ qsort(arr, 5, 4, cmp);
269
277
  // CFUNCTYPE types also work as struct fields (read back as a callable).
270
278
 
271
279
  // IMPORTANT: release the trampoline when done. Unlike Python, we cannot
272
- // rely on GC — the callback holds a libffi closure that native code may
280
+ // rely on GC — the callback holds a native trampoline that C code may
273
281
  // still reference.
274
282
  cmp.release();
275
283
  cmp2.release();
@@ -631,6 +639,12 @@ As in Python, `from_param` receives the argument as passed (also with
631
639
  `CFUNCTYPE` prototypes), its result is converted as the declared type, and
632
640
  an error it throws becomes `ArgumentError` (`"argument 1: RangeError: ..."`).
633
641
 
642
+ Non-pointer scalar CData arguments are read from their backing bytes, not an
643
+ overridden public `.value` getter. Each value is snapshotted before converting
644
+ the next argument, even without `argtypes`. A scalar `from_param` converter may
645
+ return a CData instance of another class when its native scalar kind matches
646
+ the declared type.
647
+
634
648
  Objects passed through argument adapters and the objects produced by their
635
649
  conversions stay alive while later arguments are converted and until the
636
650
  result and `errcheck` have been processed. With `callAsync()`, those temporary
@@ -987,12 +1001,23 @@ Reports record library/runtime versions, CPU, OS/kernel, buffer mode, start/
987
1001
  finish timestamps and Git revision/working-tree status. Missing CPU or Git
988
1002
  metadata produces an explicit warning rather than invented values.
989
1003
 
990
- The comparisons cover scalars, mixed arguments, short/long strings, buffer
991
- arguments, field reads and callbacks. Koffi also covers structures by value,
1004
+ Both comparisons cover narrow scalars, mixed GP/FP stack arguments, short/long
1005
+ strings, buffer arguments, field reads, scalar callbacks and 64-callback C loops.
1006
+ The node:ffi comparison includes 25 workloads. Koffi also covers structures by value,
992
1007
  variadic calls and async calls with 1/8 calls in flight. Cases without an
993
1008
  equivalent documented node:ffi API are listed as **not compared**, not
994
1009
  emulated with a different native signature.
995
1010
 
1011
+ Inferred rows omit node-ctypes `argtypes`, while both competitors use explicit
1012
+ fixed signatures for the same C functions: these rows include node-ctypes
1013
+ inference overhead, not equivalent automatic-inference APIs.
1014
+ The node:ffi bool row passes numeric `1` and compares normalized Number results:
1015
+ node:ffi represents bool arguments/results as uint8 values, whereas node-ctypes
1016
+ returns a JavaScript Boolean. Koffi's bool row uses Boolean input/output.
1017
+ The thread-safe scalar callback rows measure node-ctypes dispatch on its host
1018
+ thread against a competitor callback on the same thread, not cross-thread handoff.
1019
+ The C-loop times are per batch of 64 completed callbacks, not per callback.
1020
+
996
1021
  The `CFUNCTYPE` rows measure calls through an already-bound node-ctypes
997
1022
  prototype, against an independently bound competitor function with the same
998
1023
  C signature. Bindings are separate to avoid sharing optimization feedback
@@ -1003,8 +1028,9 @@ Both sides call the same C fixture and verify results before/after timing.
1003
1028
  String contents are encoded on every call; node-ctypes reuses scratch storage,
1004
1029
  not previously encoded strings. Measurements describe warmed repeated calls,
1005
1030
  not cold-start allocation costs.
1006
- String lengths are compared as Numbers, including conversion where the API
1007
- returns BigInt; wide integers are BigInt in both APIs. Structures are plain
1031
+ String lengths, narrow/inferred-stack i64 results and C-loop sums are compared
1032
+ as Numbers, including conversion where the API returns BigInt; wide integers
1033
+ are BigInt in both APIs. Structures are plain
1008
1034
  objects. Async times include scheduling and are reported per completed call,
1009
1035
  with the concurrency shown in the case name.
1010
1036
 
@@ -1026,9 +1052,73 @@ instead of the default HTML report. Parent directories are created automatically
1026
1052
  HTML generation runs only after all measurements finish.
1027
1053
  `benchmark_koffi.js` and `benchmark_node_ffi.js` define the actual side-by-side
1028
1054
  comparisons; `runner.js` shares timing, table output and HTML generation without
1029
- extra dependencies or a separate renderer script. There is no separate
1030
- self-benchmark command, and benchmarks are not run by the functional/parity
1031
- test suite.
1055
+ extra dependencies or a separate renderer script. Benchmarks are not run by the
1056
+ functional/parity test suite.
1057
+
1058
+ ### Native backends and upstream libffi
1059
+
1060
+ The maintained outgoing paths are the bounded C++ direct invokers and libffi.
1061
+ Callbacks use libffi closures and the shared Node-API bridge. The source tree
1062
+ stays flat, with backend-specific files prefixed where needed:
1063
+
1064
+ | Files | Responsibility |
1065
+ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
1066
+ | [call_abi.h](./src/call_abi.h), [types.h](./src/types.h) | Shared calling conventions, ABI return words and scalar conversions, without libffi headers |
1067
+ | [direct_call.h](./src/direct_call.h) | Exact fixed-signature C++ invokers |
1068
+ | [libffi_types.cc](./src/libffi_types.cc), [libffi_types.h](./src/libffi_types.h) | Primitive mapping and aggregate descriptor factories |
1069
+ | [libffi_type_cache.h](./src/libffi_type_cache.h) | Concrete owned aggregate cache used by layout metadata |
1070
+ | [libffi_call.cc](./src/libffi_call.cc), [libffi_call.h](./src/libffi_call.h) | Calling conventions, CIFs, reusable plans and worker-owned extra-call interfaces |
1071
+ | [libffi_callback.cc](./src/libffi_callback.cc), [libffi_callback.h](./src/libffi_callback.h) | Closure preparation, allocation and release |
1072
+ | [function.cc](./src/function.cc), [function.h](./src/function.h) | Node-API call orchestration, marshalling, hooks and sync/async ownership |
1073
+ | [callback.cc](./src/callback.cc), [callback.h](./src/callback.h) | Shared callback conversions, TSFN delivery, native-context hooks and lifetime |
1074
+
1075
+ CMake discovers native files with `file(GLOB_RECURSE ... CONFIGURE_DEPENDS ...)`.
1076
+ The public layouts retain their physical size/alignment; the libffi descriptor
1077
+ cache in `layout.h` is intentionally concrete rather than ABI-agnostic.
1078
+ High-level callback snapshot pooling and cached struct/array readers remain:
1079
+ slices are never recycled, retained views have independent bytes and identity,
1080
+ and custom getters, mirrored synchronization and Node-API ownership are preserved.
1081
+
1082
+ **Temporary dependency pin.** The unmodified
1083
+ [libffi submodule](https://github.com/libffi/libffi/tree/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82) is pinned to upstream commit
1084
+ [`d02afc25e8ea3aac9e78e227748e1fd7c9f14c82`](https://github.com/libffi/libffi/commit/d02afc25e8ea3aac9e78e227748e1fd7c9f14c82),
1085
+ after the v3.8.0 release. Generated version fields still report 3.8.0; the
1086
+ gitlink, not that version string, identifies the exact dependency source.
1087
+ This includes the Darwin GP-composite stack-slot
1088
+ [fix](https://github.com/libffi/libffi/commit/2472245a3430b9d24f085b7654e896e074bceb82)
1089
+ and its [compiler/ABI guard adjustment](https://github.com/libffi/libffi/commit/3365ad8b968a9b742922b6f1188462fe6ce142ec):
1090
+ small GP composites use aligned, whole-word stack slots in outgoing calls and
1091
+ closures, without widening ctypes buffers or changing scalar/HFA packing.
1092
+ This follows the compiler's C ABI rather than reproducing broken padding in
1093
+ older libffi builds, including those used by some Python installations.
1094
+
1095
+ Return to an official tag containing these fixes when released. After changing
1096
+ the submodule revision, run `npm run generate-ffi-headers`, rebuild and repeat
1097
+ the ABI/parity tests. Do not patch the vendored libffi internals.
1098
+
1099
+ **Darwin ARM64 upstream limitation.** When all GP registers are
1100
+ occupied, a byte-aligned non-HFA struct larger than 16 bytes after a narrow
1101
+ stack scalar can still misalign its indirect pointer and subsequent arguments.
1102
+ A callee dereferencing that pointer can crash. The upstream update does not
1103
+ resolve this case and this project does not disguise it by altering layouts.
1104
+ [test_function_abi.js](./tests/node_specific/test_function_abi.js) retains a
1105
+ safe C stack-tag probe for sync/async calls, temporarily skipped only on Darwin
1106
+ ARM64 until an upstream fix is available. The test remains active on other
1107
+ targets. Other supported GP/HFA/large-aggregate cases and ordinary/thread-safe
1108
+ callback ABI tests run normally.
1109
+
1110
+ **Windows ARM64 variadic HFA limitation.** A named HFA argument containing four
1111
+ doubles (32 bytes) in a variadic call triggers an access violation in upstream
1112
+ libffi, independently of the Node wrapper. Avoid this signature until an upstream
1113
+ fix is available. Its regression is temporarily skipped only on Windows ARM64
1114
+ and still runs on other targets. Native calling behavior is unchanged.
1115
+
1116
+ `CTYPES_ENABLE_DIRECT_CALLS` remains a build-time control, default ON. Fixed
1117
+ direct calls and workers need no CIF; unsupported fixed signatures use libffi,
1118
+ and async inferred/variadic calls own CIFs prepared on the JavaScript thread.
1119
+ Workers retain the parent function, metadata and library through completion.
1120
+ To compare the direct-enabled and libffi-only builds, follow the
1121
+ [native validation commands](./tests/README.md#native-backends-and-abi-regressions).
1032
1122
 
1033
1123
  ### Release validation
1034
1124
 
Binary file
Binary file
@@ -179,8 +179,9 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
179
179
  return Reflect.get(target, prop, receiver);
180
180
  }
181
181
  // Check if we already have a FunctionWrapper for this function name
182
- if (target._funcWrapperCache.has(prop)) {
183
- return target._funcWrapperCache.get(prop);
182
+ const cached = target._funcWrapperCache.get(prop);
183
+ if (cached !== undefined) {
184
+ return cached;
184
185
  }
185
186
  // Create and cache a new FunctionWrapper
186
187
  const wrapper = new FunctionWrapper(target, prop);
@@ -57,6 +57,7 @@ import { _toNativeReturnType, _toNativeTypes } from "./types.js";
57
57
  import { adaptCallbackFunction, scalarResult } from "./conversions.js";
58
58
  import { trackCallback } from "./callback-tracker.js";
59
59
  import { callbackPointer } from "../structures/helpers/common.js";
60
+ import { allocTransient } from "../memory/buffer.js";
60
61
 
61
62
  function nativeContextHook(value, name, owners) {
62
63
  if (value !== null && (typeof value === "object" || typeof value === "function")) {
@@ -174,7 +175,8 @@ function nativeContextAddresses(context, owners) {
174
175
  export function callback(fn, returnType, argTypes = [], native, abi = undefined) {
175
176
  const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
176
177
  const scalarArgs = argTypes.map(scalarResult);
177
- if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
178
+ const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
179
+ if (buffers) args.push(abi ?? "default", scalarArgs, undefined, allocTransient);
178
180
  else if (abi) args.push(abi);
179
181
  const cb = new native.Callback(...args);
180
182
 
@@ -321,7 +323,9 @@ export function threadSafeCallback(fn, returnType, argTypes = [], native, option
321
323
  );
322
324
  const args = [dispatch, _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
323
325
  const scalarArgs = argTypes.map(scalarResult);
324
- if (context !== undefined) args.push(abi ?? "default", scalarArgs, context);
326
+ const buffers = scalarArgs.some(Boolean) || args[2].some((type) => typeof type === "object" && type !== null);
327
+ if (buffers) args.push(abi ?? "default", scalarArgs, context, allocTransient);
328
+ else if (context !== undefined) args.push(abi ?? "default", scalarArgs, context);
325
329
  else if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
326
330
  else if (abi) args.push(abi);
327
331
  const cb = new native.ThreadSafeCallback(...args);
@@ -10,12 +10,24 @@ import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
10
10
  import { ArgumentError } from "../platform/errors.js";
11
11
  import { encodeWide } from "../memory/buffer.js";
12
12
  import { buildWrapper } from "../structures/helpers/wrap.js";
13
- import { activeArgumentOwners as argumentOwnerRegistry, activeOwnerStack, byrefOwners, isScalarSubclass, resolveParameter, scalarView, structArgumentFactories, structResultReaders } from "../structures/helpers/common.js";
13
+ import {
14
+ activeArgumentOwners as argumentOwnerRegistry,
15
+ activeOwnerStack,
16
+ byrefOwners,
17
+ isScalarSubclass,
18
+ resolveParameter,
19
+ scalarArgumentKind,
20
+ scalarArgumentSnapshot,
21
+ scalarArgumentValue,
22
+ scalarInstanceInfo,
23
+ scalarView,
24
+ structArgumentFactories,
25
+ structResultReaders,
26
+ } from "../structures/helpers/common.js";
14
27
 
15
28
  const activeArgumentOwners = argumentOwnerRegistry;
16
29
  // Captured at load so callback dispatch is not affected by later patches.
17
30
  const reflectApply = Reflect.apply;
18
-
19
31
  function retainArgument(owners, value) {
20
32
  if (owners !== undefined && value !== null && (typeof value === "object" || typeof value === "function")) owners.push(value);
21
33
  }
@@ -247,13 +259,19 @@ export function coerceValue(a, owners) {
247
259
 
248
260
  /**
249
261
  * Conversion of an argument beyond `argtypes` (variadic, or without
250
- * argtypes): a SimpleCData instance is passed as is, and the native call uses
251
- * its type, as Python does (`printf("%f", c_double(2.0))`).
262
+ * argtypes): a numeric SimpleCData instance keeps its type and snapshots its
263
+ * value before the next conversion (`printf("%f", c_double(2.0))`).
252
264
  */
253
265
  export function coerceVariadic(a, owners) {
266
+ if (a === null || (typeof a !== "object" && typeof a !== "function")) return a;
267
+ const info = scalarInstanceInfo(a);
268
+ if (info !== undefined) {
269
+ retainArgument(owners, a);
270
+ return scalarArgumentSnapshot(a, info);
271
+ }
254
272
  a = resolveParameter(a, owners);
255
273
  retainArgument(owners, a);
256
- if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return a;
274
+ if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return scalarArgumentSnapshot(a);
257
275
  return coerceObject(a, owners);
258
276
  }
259
277
 
@@ -276,15 +294,16 @@ export function argumentConverters(argTypes, native) {
276
294
  if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
277
295
  if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
278
296
  if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
279
- return scalarArgument(t, index);
297
+ return scalarArgument(t, kind, index);
280
298
  };
281
- return argTypes.map((t, index) => {
299
+ const converters = argTypes.map((t, index) => {
282
300
  const base = baseConverter(t, index);
283
301
  if (t === null || (typeof t !== "function" && typeof t !== "object")) return base;
284
302
  const fromParam = t.from_param;
285
303
  if (fromParam === undefined) return base;
286
304
  return fromParamArgument(t, base.fromParam ?? base, index, fromParam);
287
305
  });
306
+ return converters;
288
307
  }
289
308
 
290
309
  function pointerValue(value, native) {
@@ -346,20 +365,36 @@ function stringArgument(T, kind, index, native) {
346
365
  return convert;
347
366
  }
348
367
 
349
- function scalarArgument(T, index) {
368
+ function scalarArgument(T, kind, index) {
350
369
  const boolean = T._isBoolean === true;
351
- return (value, owners) => {
352
- if (value !== null && (typeof value === "object" || typeof value === "function")) value = resolveArgument(value, owners, index);
370
+ const stored = (value, info, owners, adapted) => {
371
+ retainArgument(owners, value);
372
+ if (!boolean && info.type !== T && !(value instanceof T) && !(adapted && info.kind === kind)) {
373
+ throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible types, ${info.type.name} instance instead of ${T.name} instance`);
374
+ }
375
+ return scalarArgumentValue(value, info);
376
+ };
377
+ const make = (adapted) => (value, owners) => {
378
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
379
+ const info = scalarInstanceInfo(value);
380
+ if (info !== undefined) return stored(value, info, owners, adapted);
381
+ value = resolveArgument(value, owners, index);
382
+ }
353
383
  if (value === null || typeof value !== "object") return value;
384
+ const info = scalarInstanceInfo(value);
385
+ if (info !== undefined) return stored(value, info, owners, adapted);
354
386
  retainArgument(owners, value);
355
387
  if (value._isSimpleCDataInstance === true) {
356
- if (!boolean && !(value instanceof T)) {
388
+ if (!boolean && !(value instanceof T) && !(adapted && scalarArgumentKind(value) === kind)) {
357
389
  throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible types, ${value.constructor.name} instance instead of ${T.name} instance`);
358
390
  }
359
- return value.value;
391
+ return scalarArgumentValue(value);
360
392
  }
361
393
  return objectMemory(value, owners);
362
394
  };
395
+ const convert = make(false);
396
+ Object.defineProperty(convert, "fromParam", { value: make(true) });
397
+ return convert;
363
398
  }
364
399
 
365
400
  function resolveArgument(value, owners, index) {
@@ -655,7 +690,11 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
655
690
  function structView(type) {
656
691
  if (typeof type === "function" && typeof type._buildStruct === "function") return (buf) => new type(buf);
657
692
  if (type !== null && typeof type === "object" && type._isStructType === true) {
658
- return (buf) => new Proxy(buf, buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true }));
693
+ let handler;
694
+ return (buf) => {
695
+ handler ??= buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true });
696
+ return new Proxy(buf, handler);
697
+ };
659
698
  }
660
699
  return null;
661
700
  }
package/lib/core/types.js CHANGED
@@ -111,7 +111,11 @@ function _buildNativeStructType(def, native) {
111
111
  if (!Number.isInteger(Math.log2(def.alignment))) {
112
112
  throw new TypeError("Native by-value ABI requires power-of-two alignment; use this layout only for memory serialization");
113
113
  }
114
- const st = new native.StructType({ union: !!def.isUnion, alignment: def.alignment, memoryClass: hasUnalignedFields(def) });
114
+ const st = new native.StructType({
115
+ union: !!def.isUnion,
116
+ alignment: def.alignment,
117
+ memoryClass: hasUnalignedFields(def),
118
+ });
115
119
  const fits = (alignment, offset) => alignment <= def.alignment && offset % alignment === 0;
116
120
 
117
121
  // La classe base è il primo membro della struct (i suoi campi sono i primi
package/lib/index.d.ts CHANGED
@@ -134,7 +134,7 @@ export type FFIType = AnyType | StructureClass | PointerTypeDef | ArrayTypeDef |
134
134
  * @example
135
135
  * ```javascript
136
136
  * import { Version } from 'node-ctypes';
137
- * console.log(Version.toString()); // "2.5.0"
137
+ * console.log(Version.toString()); // "2.8.0"
138
138
  * ```
139
139
  *
140
140
  * @category Library Loading
@@ -71,25 +71,28 @@ export function alloc(size) {
71
71
  }
72
72
 
73
73
  const kTransientPoolSize = 8192;
74
- let transientPool = new ArrayBuffer(kTransientPoolSize);
74
+ const FixedArrayBuffer = ArrayBuffer;
75
+ const bufferFrom = Buffer.from;
76
+ const zeroBuffer = Buffer.alloc;
77
+ let transientPool = new FixedArrayBuffer(kTransientPoolSize);
75
78
  let transientOffset = 0;
76
79
 
77
80
  /**
78
- * Zero-filled buffer for a value that only lives for one native call. A small
81
+ * Zero-filled buffer for a native-call temporary or an owned callback snapshot. A small
79
82
  * Buffer.alloc lives on the V8 heap and must be externalized when native code
80
83
  * reads it; slices of an off-heap pool avoid that. Slices are never reused, so
81
- * a fresh pool is already zeroed.
84
+ * a fresh pool is already zeroed. Retained slices keep their backing store alive.
82
85
  *
83
86
  * @param {number} size - Size in bytes to allocate
84
87
  * @returns {Buffer} Zero-initialized buffer
85
88
  */
86
89
  export function allocTransient(size) {
87
- if (size > kTransientPoolSize >>> 2) return Buffer.alloc(size);
90
+ if (size > kTransientPoolSize >>> 2) return zeroBuffer(size);
88
91
  if (transientOffset + size > kTransientPoolSize) {
89
- transientPool = new ArrayBuffer(kTransientPoolSize);
92
+ transientPool = new FixedArrayBuffer(kTransientPoolSize);
90
93
  transientOffset = 0;
91
94
  }
92
- const buf = Buffer.from(transientPool, transientOffset, size);
95
+ const buf = bufferFrom(transientPool, transientOffset, size);
93
96
  transientOffset += (size + 7) & ~7;
94
97
  return buf;
95
98
  }
@@ -2,12 +2,19 @@ import { flush, kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive, refre
2
2
  import { POINTER_SIZE } from "../../platform/constants.js";
3
3
 
4
4
  const simpleTypes = new WeakSet();
5
+ const scalarInstances = new WeakMap();
6
+ const scalarTypeInfos = new WeakMap();
7
+ const scalarAccessors = [];
8
+ const scalarArgumentKinds = new Set();
9
+ const scalarArgumentTypes = new Map();
10
+ const applyScalarReader = Reflect.apply;
5
11
  export const activeArgumentOwners = new Set();
6
12
  // GC roots of in-progress synchronous conversions, released in LIFO order.
7
13
  export const activeOwnerStack = [];
8
14
  export const byrefOwners = new WeakMap();
9
15
  export const structArgumentFactories = new WeakMap();
10
16
  export const structResultReaders = new WeakMap();
17
+ export const structGetters = new WeakMap();
11
18
  // Brand of callback wrappers: their constant pointer (the `_as_parameter_`
12
19
  // value), read without the generic parameter probes.
13
20
  export const callbackPointer = Symbol("callbackPointer");
@@ -48,6 +55,63 @@ export function sourceBytes(source, offset, size, name) {
48
55
 
49
56
  export function registerSimpleType(type) {
50
57
  simpleTypes.add(type);
58
+ scalarArgumentKinds.add(type._type);
59
+ }
60
+
61
+ export function scalarTypeInfo(type, swapped = false) {
62
+ let variants = scalarTypeInfos.get(type);
63
+ if (variants === undefined) {
64
+ const kind = type._type;
65
+ variants = [{ type, kind, swapped: false, pointer: type._isPointerValued === true }];
66
+ scalarTypeInfos.set(type, variants);
67
+ }
68
+ const index = swapped ? 1 : 0;
69
+ if (variants[index] === undefined) variants[index] = { ...variants[0], swapped: true };
70
+ return variants[index];
71
+ }
72
+
73
+ export function registerScalarAccessor(accessor) {
74
+ scalarAccessors.push(accessor);
75
+ }
76
+
77
+ export function registerScalarInstance(value, type, swapped = false) {
78
+ scalarInstances.set(value, scalarTypeInfo(type, swapped));
79
+ }
80
+
81
+ export function scalarInstanceInfo(value) {
82
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return undefined;
83
+ for (const accessor of scalarAccessors) {
84
+ const info = accessor(value);
85
+ if (info !== undefined) return info;
86
+ }
87
+ return scalarInstances.get(value);
88
+ }
89
+
90
+ export function scalarArgumentKind(value) {
91
+ return scalarInstanceInfo(value)?.kind;
92
+ }
93
+
94
+ export function scalarArgumentValue(value, info = scalarInstanceInfo(value)) {
95
+ if (info === undefined) return value.value;
96
+ const buffer = value._buffer;
97
+ if (mirrorsActive) refresh(buffer);
98
+ const reader = info.swapped ? info.type._readerBE : info.type._reader;
99
+ return applyScalarReader(reader, info.type, [buffer, 0]);
100
+ }
101
+
102
+ export function scalarArgumentSnapshot(value, info = scalarInstanceInfo(value)) {
103
+ if (info === undefined || info.pointer || info.kind === 0 || !scalarArgumentKinds.has(info.kind)) return value;
104
+ let constructor = scalarArgumentTypes.get(info.kind);
105
+ if (constructor === undefined) {
106
+ constructor = function ScalarArgument() {};
107
+ Object.defineProperties(constructor, {
108
+ _isSimpleCData: { value: true },
109
+ _type: { value: info.kind },
110
+ });
111
+ scalarArgumentTypes.set(info.kind, constructor);
112
+ }
113
+ // Keep the inferred type, but snapshot the value before the next adapter.
114
+ return { constructor, value: scalarArgumentValue(value, info) };
51
115
  }
52
116
 
53
117
  export function isScalarSubclass(type) {
@@ -60,7 +124,9 @@ export function scalarView(type, buffer, swapped = false) {
60
124
  const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
61
125
  value._buffer = buffer;
62
126
  if (base !== undefined) value[kMirrorBase] = base;
63
- if (swapped && type._readerBE && type._writerBE) {
127
+ const useSwapped = !!(swapped && type._readerBE && type._writerBE);
128
+ registerScalarInstance(value, type, useSwapped);
129
+ if (useSwapped) {
64
130
  Object.defineProperty(value, "value", {
65
131
  get() {
66
132
  if (base !== undefined) refresh(buffer);
@@ -38,7 +38,7 @@ import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
39
  import { isMirror, syncDefinition } from "../../memory/mirror.js";
40
40
  import { allocTransient } from "../../memory/buffer.js";
41
- import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, structResultReaders, writePointerField } from "./common.js";
41
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, structGetters, structResultReaders, writePointerField } from "./common.js";
42
42
 
43
43
  /**
44
44
  * Creates a struct type definition with proper alignment and padding.
@@ -733,5 +733,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
733
733
  }
734
734
  }
735
735
 
736
- return syncDefinition(structDef);
736
+ syncDefinition(structDef);
737
+ structGetters.set(structDef, structDef.get);
738
+ return structDef;
737
739
  }
@@ -38,7 +38,7 @@ import { bitFieldAccessors } from "./bitfield.js";
38
38
  import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
39
39
  import { buildWrapper } from "./wrap.js";
40
40
  import { syncDefinition } from "../../memory/mirror.js";
41
- import { clearKeepAlives, copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
41
+ import { clearKeepAlives, copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, structGetters, writePointerField } from "./common.js";
42
42
 
43
43
  /**
44
44
  * Creates a union type definition where all fields share offset 0.
@@ -602,5 +602,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
602
602
  },
603
603
  };
604
604
 
605
- return syncDefinition(unionDef);
605
+ syncDefinition(unionDef);
606
+ structGetters.set(unionDef, unionDef.get);
607
+ return unionDef;
606
608
  }
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import { mirroredAccessors } from "../../memory/mirror.js";
22
+ import { structGetters } from "./common.js";
22
23
 
23
24
  // Proprietà meta del Buffer che NON vanno mai interpretate come field name.
24
25
  // Per i campi Proxy passano direttamente attraverso al target buffer.
@@ -67,6 +68,18 @@ export function buildWrapper(def, { instanceTag, exposeAnonymous, mirrored = fal
67
68
  function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
68
69
  const { fieldMap, anonymousFieldNames } = def;
69
70
  const { fieldReaders, fieldWriters } = mirrored ? mirroredAccessors(def) : def;
71
+ const get = structGetters.get(def);
72
+ const arrayReaders = Object.create(null);
73
+ if (!mirrored && get !== undefined) {
74
+ for (const field of def.fields) {
75
+ if (field.isArray) {
76
+ arrayReaders[field.name] = (buf) => {
77
+ const view = buf.subarray(field.offset, field.offset + field.size);
78
+ return field.type._charKind !== undefined ? field.type.getValue(view) : field.type.wrap(view);
79
+ };
80
+ }
81
+ }
82
+ }
70
83
 
71
84
  // Precalcola la lista di chiavi visibili (stabile durante tutta la vita
72
85
  // del def). Evita di ricostruirla a ogni Object.keys / {...spread} / ecc.
@@ -89,15 +102,13 @@ function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
89
102
  if (typeof prop === "string" && BUFFER_META_PROPS.has(prop)) return target[prop];
90
103
 
91
104
  if (typeof prop === "string") {
92
- // FAST PATH: reader precompilato (scalari, POINTER, bitfield).
93
- // NB: questa è la differenza chiave rispetto ai 2 vecchi proxy
94
- // nested che non usavano fieldReaders — ora anche loro ottengono
95
- // il fast path gratis.
96
105
  if (fieldReaders !== undefined) {
97
106
  const r = fieldReaders[prop];
98
107
  if (r !== undefined) return r(target);
99
108
  }
100
- // FALLBACK: tipi complessi (nested/array) e anonymous subfields.
109
+ const arrayReader = arrayReaders[prop];
110
+ if (arrayReader !== undefined && def.get === get) return arrayReader(target);
111
+ // Mirrored arrays, nested fields and anonymous subfields use def.get.
101
112
  if (fieldMap?.has(prop) || (exposeAnonymous && anonymousFieldNames?.[prop] === true)) {
102
113
  return def.get(target, prop);
103
114
  }
@@ -46,7 +46,7 @@
46
46
  * ```
47
47
  */
48
48
 
49
- import { copyInstance, inDllBuffer, scalarOutparam, scalarView, sourceBytes } from "../structures/helpers/common.js";
49
+ import { copyInstance, inDllBuffer, registerScalarAccessor, scalarOutparam, scalarTypeInfo, scalarView, sourceBytes } from "../structures/helpers/common.js";
50
50
 
51
51
  /**
52
52
  * Creates the SimpleCData base class with required dependencies injected.
@@ -103,12 +103,19 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
103
103
  * ```
104
104
  */
105
105
  class SimpleCData {
106
+ #scalarInfo;
107
+
108
+ static {
109
+ registerScalarAccessor((value) => (#scalarInfo in value ? value.#scalarInfo : undefined));
110
+ }
111
+
106
112
  /**
107
113
  * @param {number|bigint} [value] - Initial value (default: 0)
108
114
  */
109
115
  constructor(value) {
110
116
  const Ctor = this.constructor;
111
117
  this._buffer = alloc(Ctor._size);
118
+ this.#scalarInfo = scalarTypeInfo(Ctor);
112
119
  if (value !== undefined) {
113
120
  this.value = value;
114
121
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "2.7.0",
3
+ "version": "2.9.0",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",