node-ctypes 2.1.0 → 2.2.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
@@ -292,8 +292,34 @@ const r2 = RECT.from_address(malloc_result);
292
292
 
293
293
  // Bind a C-exported global (Python: c_int.in_dll)
294
294
  const tz = c_int32.in_dll(libc, "_timezone");
295
+
296
+ // Raw bytes at an address (Python: (c_ubyte * n).from_address(addr));
297
+ // `bytes._buffer` is a Buffer over that memory, as Python's memoryview()
298
+ const bytes = array(c_uint8, 64).from_address(malloc_result);
299
+ const view = new Float32Array(bytes._buffer.buffer, bytes._buffer.byteOffset, 16);
295
300
  ```
296
301
 
302
+ ### Electron
303
+
304
+ Electron does not allow Buffers over memory that V8 did not allocate, so a
305
+ Buffer *view* of native memory cannot exist there. node-ctypes detects this
306
+ when it loads (`EXTERNAL_BUFFERS` is `false`) and keeps the same API:
307
+
308
+ - instances on native memory (`from_address`, `in_dll`, `pointer.contents`,
309
+ `p[i]`, pointer fields) work on a copy that is re-read before every access
310
+ and written back after every assignment, so they still see what C writes
311
+ and C sees what JavaScript writes;
312
+ - passed to a C function, `addressof()`, `pointer()`, `memmove()` and
313
+ `memset()`, such an instance uses the original address;
314
+ - the `_buffer` of such an instance is the copy: a typed array or Buffer
315
+ method over it does not read or write native memory. Use the instance
316
+ (`arr[i]`, `s.field`) or `memmove()`.
317
+
318
+ Only the bytes of the accessed field are copied, one native call per read
319
+ or write (about 50 ns); instances on ordinary Buffers (`new Point()`,
320
+ `c_int(5)`) have no extra cost. Set `NODE_CTYPES_NO_EXTERNAL_BUFFERS=1`
321
+ to run in this mode on Node.js.
322
+
297
323
  ### Adapter protocols: `_as_parameter_` and `from_param`
298
324
 
299
325
  ```javascript
@@ -527,6 +553,7 @@ Each example in `examples/` has its own README; see the [index](examples/README.
527
553
 
528
554
  ```bash
529
555
  cd tests && npm install && npm run test # unit tests (JS + Python parity)
556
+ NODE_CTYPES_NO_EXTERNAL_BUFFERS=1 npm test # again as in Electron (from tests/)
530
557
  npm run test:types # type-check lib/index.d.ts (tests/types)
531
558
  npm run docs # TypeDoc API site in docs/
532
559
  npm run docs:serve # preview
Binary file
Binary file
@@ -6,11 +6,15 @@
6
6
  * conversion).
7
7
  */
8
8
 
9
+ import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
10
+
9
11
  /**
10
12
  * Base conversion of an object argument:
11
13
  * - struct/union/array instance or Buffer view → its Buffer (by reference)
12
14
  * - pointer created from an address → the address
13
15
  * - object with `_as_parameter_` (callbacks, adapters) → that value
16
+ * - copy of native memory (no external buffers, memory/mirror.js) → the
17
+ * original address
14
18
  * - anything else unchanged
15
19
  */
16
20
  export function coerceObject(a) {
@@ -20,12 +24,29 @@ export function coerceObject(a) {
20
24
  // Puntatore creato da indirizzo (fromAddress): senza Buffer va passato
21
25
  // l'indirizzo, altrimenti al C arriverebbe NULL.
22
26
  if (b === null && a._pointerType !== undefined) return a.address;
27
+ if (mirrorsActive) return mirrorAddress(b) ?? b;
23
28
  return b;
24
29
  }
25
30
  if (a._as_parameter_ !== undefined) return a._as_parameter_;
31
+ if (mirrorsActive) return mirrorAddress(a) ?? a;
26
32
  return a;
27
33
  }
28
34
 
35
+ // Struct/union passato per valore: il nativo copia i byte del Buffer, che per
36
+ // una copia di memoria nativa vanno prima riletti.
37
+ function coerceStructValue(a) {
38
+ if (a !== null && typeof a === "object") {
39
+ const b = Buffer.isBuffer(a._buffer) ? a._buffer : a;
40
+ if (Buffer.isBuffer(b)) {
41
+ refresh(b);
42
+ return b;
43
+ }
44
+ }
45
+ return coerceObject(a);
46
+ }
47
+
48
+ const isStructType = (t) => t !== null && (typeof t === "function" || typeof t === "object") && (typeof t._buildStruct === "function" || typeof t._buildUnion === "function" || t._isStructType === true);
49
+
29
50
  /**
30
51
  * Python default conversion (no argtypes, variadic arguments): a SimpleCData
31
52
  * instance is passed by value (`abs(c_int(-5))`), other objects as
@@ -50,6 +71,7 @@ export function coerceValue(a) {
50
71
  export function argumentConverters(argTypes, native) {
51
72
  const pointerKinds = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
52
73
  return argTypes.map((t) => {
74
+ if (mirrorsActive && isStructType(t)) return coerceStructValue;
53
75
  if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
54
76
  if (!pointerKinds.has(t._type)) return coerceValue;
55
77
  return (a) => {
@@ -25,16 +25,14 @@
25
25
  *
26
26
  * @example COM vtable dispatch
27
27
  * ```javascript
28
- * import { WINFUNCTYPE, c_int32, c_void_p, ptrToBuffer } from 'node-ctypes';
28
+ * import { WINFUNCTYPE, POINTER, c_int32, c_void_p } from 'node-ctypes';
29
29
  *
30
- * // Read vtable pointer from COM object
31
- * const vtableBuf = ptrToBuffer(objPtr, 8);
32
- * const vtableAddr = vtableBuf.readBigUInt64LE(0);
33
- * const vtable = ptrToBuffer(vtableAddr, 24); // 3 IUnknown methods * 8 bytes
30
+ * // The first field of a COM object is the address of its vtable
31
+ * const vtable = POINTER(c_void_p).fromAddress(c_void_p.from_address(objPtr).value);
34
32
  *
35
33
  * // QueryInterface is the first vtable entry
36
34
  * const QueryInterface = WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p);
37
- * const qi = QueryInterface(vtable.readBigUInt64LE(0));
35
+ * const qi = QueryInterface(vtable[0]);
38
36
  * ```
39
37
  */
40
38
 
package/lib/index.d.ts CHANGED
@@ -914,6 +914,21 @@ export interface ArrayTypeDef<E = any> {
914
914
  create(values?: ReadonlyArray<ArrayElementArg<E>> | string): ArrayInstance<E>;
915
915
  /** Wrap an existing buffer as an array with index access. */
916
916
  wrap(buffer: Buffer): ArrayInstance<E>;
917
+ /**
918
+ * Array sharing the memory of `source` from `offset` (Python:
919
+ * `(c_int * 3).from_buffer(source, offset)`).
920
+ */
921
+ from_buffer(source: Buffer | Uint8Array | { _buffer: Buffer }, offset?: number): ArrayInstance<E>;
922
+ /** Array with a copy of the bytes of `source` from `offset` (Python: `from_buffer_copy`). */
923
+ from_buffer_copy(source: Buffer | Uint8Array | { _buffer: Buffer }, offset?: number): ArrayInstance<E>;
924
+ /**
925
+ * Array on the memory at `address` (Python: `(c_int * 3).from_address(address)`).
926
+ * Its `_buffer` is a Buffer over that memory, as Python's
927
+ * `memoryview((c_char * n).from_address(address))`; where
928
+ * {@link EXTERNAL_BUFFERS} is `false` it is a copy kept in sync by the
929
+ * array's element accesses.
930
+ */
931
+ from_address(address: bigint | number): ArrayInstance<E>;
917
932
  }
918
933
 
919
934
  /**
@@ -923,6 +938,12 @@ export interface ArrayTypeDef<E = any> {
923
938
  export interface ArrayProxy<T = any> {
924
939
  [index: number]: T;
925
940
  [Symbol.iterator](): Iterator<T>;
941
+ /**
942
+ * The Buffer of the array: for an array on native memory
943
+ * ({@link ArrayTypeDef.from_address}) a Buffer over that memory, as
944
+ * Python's `memoryview()` (a copy where {@link EXTERNAL_BUFFERS} is `false`).
945
+ */
946
+ readonly _buffer: Buffer;
926
947
  }
927
948
 
928
949
  /**
@@ -1688,18 +1709,6 @@ export function sizeof(type: AnyType | StructDef | ArrayTypeDef | StructureClass
1688
1709
  */
1689
1710
  export function alignment(type: AnyType | StructDef | ArrayTypeDef | StructureClass | PointerTypeDef | FuncPtrFactory | SimpleCDataInstance | Structure<any>): number;
1690
1711
 
1691
- /**
1692
- * Create a Buffer view of native memory at a given address.
1693
- *
1694
- * **Warning:** Use with caution — the buffer is not bounds-checked.
1695
- *
1696
- * @param address - Native memory address
1697
- * @param size - Number of bytes
1698
- *
1699
- * @category Memory
1700
- */
1701
- export function ptrToBuffer(address: bigint | number, size: number): Buffer;
1702
-
1703
1712
  /**
1704
1713
  * Define a struct using the functional API.
1705
1714
  *
@@ -2393,6 +2402,15 @@ export const SimpleCData: SimpleCDataConstructor;
2393
2402
  */
2394
2403
  export const POINTER_SIZE: number;
2395
2404
 
2405
+ /**
2406
+ * `false` where the runtime does not allow Buffers over native memory
2407
+ * (Electron, or `NODE_CTYPES_NO_EXTERNAL_BUFFERS=1`). ctypes instances on
2408
+ * native memory (`from_address`, `in_dll`, pointers) then work on a
2409
+ * synchronized copy, and their `_buffer` is that copy.
2410
+ * @category Constants
2411
+ */
2412
+ export const EXTERNAL_BUFFERS: boolean;
2413
+
2396
2414
  /**
2397
2415
  * Size of `wchar_t` in bytes (2 on Windows, 4 on Unix).
2398
2416
  * @category Constants
package/lib/index.js CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  memset as _memset,
40
40
  } from "./memory/buffer.js";
41
41
  import { createMemoryOps } from "./memory/operations.js";
42
+ import { enableMirrors, wrapNative } from "./memory/mirror.js";
42
43
  import { addressOf as _addressOf, byref as _byref, cast as _cast, ptrToBuffer as _ptrToBuffer, POINTER as _POINTER, pointer as _pointer } from "./memory/pointer.js";
43
44
  import { FormatError as _FormatError, WinError as _WinError, ArgumentError } from "./platform/errors.js";
44
45
  import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField } from "./structures/helpers/common.js";
@@ -98,7 +99,14 @@ const findNativeModule = () => {
98
99
  };
99
100
 
100
101
  const require = createRequire(import.meta.url);
101
- const native = require(findNativeModule());
102
+ const rawNative = require(findNativeModule());
103
+
104
+ // Senza Buffer esterni (Electron) le view sulla memoria nativa diventano copie
105
+ // sincronizzate (memory/mirror.js). NODE_CTYPES_NO_EXTERNAL_BUFFERS=1 forza la
106
+ // stessa modalità su Node.js, per provarla senza Electron.
107
+ const externalBuffers = rawNative.externalBuffersAllowed !== false && process.env.NODE_CTYPES_NO_EXTERNAL_BUFFERS !== "1";
108
+ if (!externalBuffers) enableMirrors(rawNative);
109
+ const native = externalBuffers ? rawNative : wrapNative(rawNative);
102
110
 
103
111
  // Initialize platform constants from native module
104
112
  _initConstants(native);
@@ -256,6 +264,8 @@ function cast(ptr, targetType) {
256
264
  return _cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native);
257
265
  }
258
266
 
267
+ // Uso interno (from_address, cast, ...): una view della memoria nativa, o una
268
+ // copia sincronizzata dove i Buffer esterni non sono permessi.
259
269
  function ptrToBuffer(address, size) {
260
270
  return _ptrToBuffer(address, size, native);
261
271
  }
@@ -352,7 +362,7 @@ memoryDeps.Union = Union;
352
362
  * console.log(arr[2]); // 42
353
363
  */
354
364
  function array(elementType, count) {
355
- return _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p);
365
+ return _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p, ptrToBuffer);
356
366
  }
357
367
 
358
368
  // ============================================================================
@@ -595,7 +605,6 @@ export {
595
605
  writeValue,
596
606
  sizeof,
597
607
  alignment,
598
- ptrToBuffer,
599
608
 
600
609
  // Strutture
601
610
  struct,
@@ -684,6 +693,10 @@ export {
684
693
  // Re-export constants from platform module
685
694
  export { POINTER_SIZE, WCHAR_SIZE, NULL } from "./platform/constants.js";
686
695
 
696
+ // false dove i Buffer su memoria nativa non sono permessi (Electron): le
697
+ // istanze su memoria nativa usano una copia sincronizzata (memory/mirror.js).
698
+ export const EXTERNAL_BUFFERS = externalBuffers;
699
+
687
700
  // Python ctypes.util.find_library equivalent
688
701
  export { find_library } from "./platform/find_library.js";
689
702
 
@@ -27,6 +27,8 @@
27
27
  * ```
28
28
  */
29
29
 
30
+ import { mirrorAddress } from "./mirror.js";
31
+
30
32
  /**
31
33
  * Allocates a zero-initialized buffer of the specified size.
32
34
  *
@@ -447,25 +449,36 @@ export function wstring_at(address, size, native) {
447
449
  * ```
448
450
  */
449
451
  export function memmove(dst, src, count, native) {
450
- const srcBuf = memoryOf(src, count, native, "src");
451
- srcBuf.copy(memoryOf(dst, count, native, "dst"), 0, 0, count);
452
+ const to = memoryOf(dst, native, "dst");
453
+ const from = memoryOf(src, native, "src");
454
+ // Come Buffer.copy, la copia si ferma alla fine dei Buffer coinvolti.
455
+ let n = count;
456
+ if (typeof to !== "bigint") n = Math.min(n, to.length);
457
+ if (typeof from !== "bigint") n = Math.min(n, from.length);
458
+ if (n <= 0) return;
459
+ if (typeof to !== "bigint" && typeof from !== "bigint") from.copy(to, 0, 0, n);
460
+ else native.memmove(to, from, n);
452
461
  }
453
462
 
454
463
  // Memoria di un argomento di memmove/memset, come Python: Buffer, istanze
455
464
  // ctypes (struct, array, c_*), puntatori o un indirizzo (BigInt/number).
456
- function memoryOf(value, count, native, name) {
465
+ // Gli indirizzi (anche quello originale di una copia, memory/mirror.js) sono
466
+ // letti e scritti dal nativo, senza creare un Buffer esterno.
467
+ function memoryOf(value, native, name) {
457
468
  if (value !== null && typeof value === "object") {
458
- if (Buffer.isBuffer(value._buffer)) return value._buffer;
459
- if (value._pointerType !== undefined) return native.ptrToBuffer(value.address, count);
460
- if (value instanceof Uint8Array) return value;
461
- }
462
- if (typeof value === "bigint" || typeof value === "number") {
463
- if (!value) throw new TypeError(`${name} is a NULL pointer`);
464
- return native.ptrToBuffer(value, count);
469
+ if (Buffer.isBuffer(value._buffer)) return mirrorAddress(value._buffer) ?? value._buffer;
470
+ if (value._pointerType !== undefined) return addressOrNull(value.address, name);
471
+ if (value instanceof Uint8Array) return mirrorAddress(value) ?? value;
465
472
  }
473
+ if (typeof value === "bigint" || typeof value === "number") return addressOrNull(value, name);
466
474
  throw new TypeError(`${name} must be a Buffer, a ctypes instance, a pointer or an address`);
467
475
  }
468
476
 
477
+ function addressOrNull(value, name) {
478
+ if (!value) throw new TypeError(`${name} is a NULL pointer`);
479
+ return BigInt(value);
480
+ }
481
+
469
482
  /**
470
483
  * Fills memory with a byte value (like C's memset).
471
484
  *
@@ -487,5 +500,10 @@ function memoryOf(value, count, native, name) {
487
500
  * ```
488
501
  */
489
502
  export function memset(dst, value, count, native) {
490
- memoryOf(dst, count, native, "dst").fill(value, 0, count);
503
+ const to = memoryOf(dst, native, "dst");
504
+ if (typeof to !== "bigint") {
505
+ to.fill(value, 0, count);
506
+ } else if (count > 0) {
507
+ native.memmove(to, Buffer.alloc(count, value), count);
508
+ }
491
509
  }
@@ -0,0 +1,283 @@
1
+ /**
2
+ * @file mirror.js
3
+ * @module memory/mirror
4
+ * @description Memory access where external buffers are not allowed.
5
+ *
6
+ * Electron (V8 memory cage) forbids Buffers over memory not allocated by V8,
7
+ * so the library cannot create a view of native memory. There, the view
8
+ * is replaced by a "mirror": a V8 Buffer with a copy of the bytes, registered
9
+ * with the address it mirrors. ctypes instances on a mirror (`from_address`,
10
+ * `in_dll`, `pointer.contents`, ...) stay live: every read refreshes the
11
+ * bytes from native memory, every write is copied back, and FFI arguments,
12
+ * `addressof()` and pointers use the original address.
13
+ *
14
+ * On Node.js the mirrors are never created and every function here returns
15
+ * immediately.
16
+ */
17
+
18
+ // Indirizzo nativo di ogni ArrayBuffer specchio. Buffer.alloc non usa il pool,
19
+ // quindi l'ArrayBuffer è solo della copia e le sotto-view (subarray) la
20
+ // ritrovano con l'indirizzo base + byteOffset. L'indirizzo è un Number quando
21
+ // è esatto (sotto 2^53, cioè sempre in user space), altrimenti un BigInt: la
22
+ // somma di Number non alloca.
23
+ const bases = new WeakMap();
24
+
25
+ let raw = null;
26
+
27
+ /**
28
+ * True when external buffers are not allowed and mirrors are used.
29
+ * @type {boolean}
30
+ */
31
+ export let mirrorsActive = false;
32
+
33
+ /**
34
+ * Enable mirrors for the given native module.
35
+ *
36
+ * @param {Object} native - Native module (unwrapped)
37
+ */
38
+ export function enableMirrors(native) {
39
+ raw = native;
40
+ mirrorsActive = true;
41
+ }
42
+
43
+ const toBase = (address) => {
44
+ const n = Number(address);
45
+ return Number.isSafeInteger(n) ? n : BigInt(address);
46
+ };
47
+ const at = (base, offset) => (typeof base === "number" ? base + offset : base + BigInt(offset));
48
+
49
+ /**
50
+ * Wrap the native module: `ptrToBuffer` returns a mirror, the address of a
51
+ * mirror is the native one. Reads and writes on a mirror stay on the copy,
52
+ * like the JS readers/writers, and are synchronized by refresh()/flush().
53
+ *
54
+ * @param {Object} native - Native module
55
+ * @returns {Object} Native module with mirror-aware memory functions
56
+ */
57
+ export function wrapNative(native) {
58
+ return Object.create(native, {
59
+ ptrToBuffer: { value: (address, size) => mirrorBuffer(address, size) },
60
+ addressOf: { value: (buf) => mirrorAddress(buf) ?? native.addressOf(buf) },
61
+ // Un Buffer specchio scritto come valore puntatore vale il suo indirizzo.
62
+ writeValue: { value: (ptr, type, value, offset) => native.writeValue(ptr, type, mirrorAddress(value) ?? value, offset) },
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Copy `size` bytes at `address` into a new mirror Buffer.
68
+ *
69
+ * @param {bigint|number} address - Native address
70
+ * @param {number} size - Size in bytes
71
+ * @returns {Buffer|null} Mirror, `null` for a NULL address
72
+ */
73
+ export function mirrorBuffer(address, size) {
74
+ const base = toBase(address);
75
+ if (base === 0 || base === 0n) return null;
76
+ if (typeof size !== "number" || !(size > 0)) throw new RangeError("Invalid buffer size");
77
+ const buf = Buffer.alloc(size);
78
+ raw.readMemory(buf, 0, size, base);
79
+ bases.set(buf.buffer, base);
80
+ return buf;
81
+ }
82
+
83
+ /**
84
+ * True if `buf` is a mirror (or a subarray of one).
85
+ *
86
+ * @param {*} buf - Any value
87
+ * @returns {boolean}
88
+ */
89
+ export function isMirror(buf) {
90
+ return mirrorsActive && buf instanceof Uint8Array && bases.has(buf.buffer);
91
+ }
92
+
93
+ /**
94
+ * Native address mirrored by a Buffer (or a subarray of a mirror).
95
+ *
96
+ * @param {*} buf - Any value
97
+ * @returns {bigint|undefined} Address, `undefined` if not a mirror
98
+ */
99
+ export function mirrorAddress(buf) {
100
+ if (!mirrorsActive || !(buf instanceof Uint8Array)) return undefined;
101
+ const base = bases.get(buf.buffer);
102
+ return base === undefined ? undefined : BigInt(at(base, buf.byteOffset));
103
+ }
104
+
105
+ /**
106
+ * Symbol of the native address of an instance on a mirror, saved when the
107
+ * instance is created so that each access skips the lookup.
108
+ */
109
+ export const kMirrorBase = Symbol("mirrorBase");
110
+
111
+ /**
112
+ * Native address of the first byte of a mirror, as stored (Number when
113
+ * exact, otherwise BigInt).
114
+ *
115
+ * @param {*} buf - Any value
116
+ * @returns {number|bigint|undefined} Address, `undefined` if not a mirror
117
+ */
118
+ export function mirrorBase(buf) {
119
+ if (!(buf instanceof Uint8Array)) return undefined;
120
+ const base = bases.get(buf.buffer);
121
+ return base === undefined ? undefined : at(base, buf.byteOffset);
122
+ }
123
+
124
+ /**
125
+ * Refresh a mirror (or a range of it) with the current native bytes.
126
+ *
127
+ * @param {Buffer} buf - Buffer, ignored if not a mirror
128
+ * @param {number} [offset=0] - Start of the range in `buf`
129
+ * @param {number} [length] - Length of the range (default: to the end)
130
+ */
131
+ export function refresh(buf, offset = 0, length = buf.length - offset) {
132
+ if (!mirrorsActive || length <= 0) return;
133
+ const base = bases.get(buf.buffer);
134
+ if (base !== undefined) raw.readMemory(buf, offset, length, at(base, buf.byteOffset + offset));
135
+ }
136
+
137
+ /**
138
+ * Copy a mirror (or a range of it) back to native memory.
139
+ *
140
+ * @param {Buffer} buf - Buffer, ignored if not a mirror
141
+ * @param {number} [offset=0] - Start of the range in `buf`
142
+ * @param {number} [length] - Length of the range (default: to the end)
143
+ */
144
+ export function flush(buf, offset = 0, length = buf.length - offset) {
145
+ if (!mirrorsActive || length <= 0) return;
146
+ const base = bases.get(buf.buffer);
147
+ if (base !== undefined) raw.writeMemory(buf, offset, length, at(base, buf.byteOffset + offset));
148
+ }
149
+
150
+ // Byte di un campo da sincronizzare: l'unità di memoria per i bitfield.
151
+ const fieldSize = (field) => (field.isBitField ? field.baseSize : field.size);
152
+
153
+ const mirroredCache = new WeakMap();
154
+
155
+ /**
156
+ * Field readers and writers of a struct/union definition for instances on a
157
+ * mirror: a read refreshes the bytes of the field, a write copies them back
158
+ * (a bitfield refreshes its storage unit first). Instances on ordinary
159
+ * Buffers keep using `def.fieldReaders` / `def.fieldWriters` unchanged.
160
+ *
161
+ * @param {Object} def - structDef / unionDef
162
+ * @returns {{fieldReaders: Object, fieldWriters: Object}}
163
+ */
164
+ export function mirroredAccessors(def) {
165
+ let accessors = mirroredCache.get(def);
166
+ if (accessors !== undefined) return accessors;
167
+ const fieldReaders = Object.create(null);
168
+ const fieldWriters = Object.create(null);
169
+ for (const field of def.fields) {
170
+ const read = def.fieldReaders?.[field.name];
171
+ const write = def.fieldWriters?.[field.name];
172
+ const offset = field.offset;
173
+ const size = fieldSize(field);
174
+ // `base` è l'indirizzo del Buffer, salvato nell'istanza (Structure) o
175
+ // cercato (struct annidate).
176
+ if (read !== undefined) {
177
+ fieldReaders[field.name] = (buf, base = mirrorBase(buf)) => {
178
+ raw.readMemory(buf, offset, size, at(base, offset));
179
+ return read(buf);
180
+ };
181
+ }
182
+ if (write !== undefined) {
183
+ // Un campo intero viene sovrascritto, quindi basta ricopiarlo; un
184
+ // bitfield cambia solo alcuni bit dell'unità, che va prima riletta.
185
+ fieldWriters[field.name] = field.isBitField
186
+ ? (buf, value, base = mirrorBase(buf)) => {
187
+ raw.readMemory(buf, offset, size, at(base, offset));
188
+ write(buf, value);
189
+ raw.writeMemory(buf, offset, size, at(base, offset));
190
+ }
191
+ : (buf, value, base = mirrorBase(buf)) => {
192
+ write(buf, value);
193
+ raw.writeMemory(buf, offset, size, at(base, offset));
194
+ };
195
+ }
196
+ }
197
+ accessors = { fieldReaders, fieldWriters };
198
+ mirroredCache.set(def, accessors);
199
+ return accessors;
200
+ }
201
+
202
+ /**
203
+ * Make `get` / `set` / `toObject` of a struct/union definition mirror-aware
204
+ * (the generic paths: nested fields, arrays, instance methods, readValue).
205
+ * A named field syncs only its bytes; nested structures and arrays sync
206
+ * themselves on access. Applied only when mirrors are active; Buffers that
207
+ * are not mirrors cost one lookup.
208
+ *
209
+ * @param {Object} def - structDef / unionDef
210
+ * @returns {Object} The same definition
211
+ */
212
+ export function syncDefinition(def) {
213
+ if (!mirrorsActive) return def;
214
+ const size = def.size;
215
+ const fieldMap = def.fieldMap;
216
+ const { get, set, toObject } = def;
217
+ def.get = function (bufOrObj, fieldName) {
218
+ if (isMirror(bufOrObj)) {
219
+ const field = fieldMap?.get(fieldName);
220
+ if (field === undefined) refresh(bufOrObj, 0, size);
221
+ else if (!field.isNested && !field.isArray) refresh(bufOrObj, field.offset, fieldSize(field));
222
+ }
223
+ return get.call(this, bufOrObj, fieldName);
224
+ };
225
+ def.set = function (bufOrObj, fieldName, value) {
226
+ if (!isMirror(bufOrObj)) return set.call(this, bufOrObj, fieldName, value);
227
+ const field = fieldMap?.get(fieldName);
228
+ const whole = field === undefined || field.isNested || field.isArray || field.isBitField;
229
+ const offset = whole ? 0 : field.offset;
230
+ const length = whole ? size : fieldSize(field);
231
+ if (whole) refresh(bufOrObj, offset, length);
232
+ const result = set.call(this, bufOrObj, fieldName, value);
233
+ flush(bufOrObj, offset, length);
234
+ return result;
235
+ };
236
+ def.toObject = function (bufOrObj) {
237
+ if (isMirror(bufOrObj)) refresh(bufOrObj, 0, size);
238
+ return toObject.call(this, bufOrObj);
239
+ };
240
+ return def;
241
+ }
242
+
243
+ const simpleCache = new WeakMap();
244
+
245
+ // Accessor `value` ereditato (le sottoclassi possono ridefinirlo).
246
+ function inheritedValue(proto) {
247
+ for (let p = proto; p !== null; p = Object.getPrototypeOf(p)) {
248
+ const descriptor = Object.getOwnPropertyDescriptor(p, "value");
249
+ if (descriptor !== undefined) return descriptor;
250
+ }
251
+ return undefined;
252
+ }
253
+
254
+ /**
255
+ * Prototype for SimpleCData instances on a mirror (with `kMirrorBase` set):
256
+ * `value` refreshes the bytes before reading and copies them back after
257
+ * writing. Instances on ordinary Buffers keep the class prototype, without
258
+ * any check.
259
+ *
260
+ * @param {Function} Ctor - SimpleCData class
261
+ * @returns {Object} Prototype inheriting from `Ctor.prototype`
262
+ */
263
+ export function mirroredPrototype(Ctor) {
264
+ let proto = simpleCache.get(Ctor);
265
+ if (proto !== undefined) return proto;
266
+ const { get, set } = inheritedValue(Ctor.prototype);
267
+ const size = Ctor._size;
268
+ proto = Object.create(Ctor.prototype, {
269
+ value: {
270
+ configurable: true,
271
+ get() {
272
+ raw.readMemory(this._buffer, 0, size, this[kMirrorBase]);
273
+ return get.call(this);
274
+ },
275
+ set(value) {
276
+ set.call(this, value);
277
+ raw.writeMemory(this._buffer, 0, size, this[kMirrorBase]);
278
+ },
279
+ },
280
+ });
281
+ simpleCache.set(Ctor, proto);
282
+ return proto;
283
+ }
@@ -27,6 +27,8 @@
27
27
  * ```
28
28
  */
29
29
 
30
+ import { flush, mirrorsActive, refresh } from "./mirror.js";
31
+
30
32
  /**
31
33
  * Factory che cattura le dipendenze in closure e restituisce un bundle di
32
34
  * funzioni memory-op con signature logica pulita.
@@ -117,6 +119,7 @@ export function createMemoryOps(deps) {
117
119
  if (offset + size > ptr.length) {
118
120
  throw new RangeError(`Read would exceed buffer bounds (offset: ${offset}, size: ${size}, buffer length: ${ptr.length})`);
119
121
  }
122
+ if (mirrorsActive) refresh(ptr, offset, size);
120
123
  return type._reader(ptr, offset);
121
124
  }
122
125
  if (typeof ptr === "bigint" || typeof ptr === "number") {
@@ -173,6 +176,7 @@ export function createMemoryOps(deps) {
173
176
  throw new RangeError(`Write would exceed buffer bounds (offset: ${offset}, size: ${size}, buffer length: ${ptr.length})`);
174
177
  }
175
178
  type._writer(ptr, offset, value);
179
+ if (mirrorsActive) flush(ptr, offset, size);
176
180
  return type._size;
177
181
  }
178
182
 
@@ -182,6 +186,7 @@ export function createMemoryOps(deps) {
182
186
  const tempBuf = ptr.subarray(offset, offset + def.size);
183
187
  if (Buffer.isBuffer(value)) {
184
188
  value.copy(tempBuf, 0, 0, def.size);
189
+ if (mirrorsActive) flush(tempBuf);
185
190
  } else if (typeof value === "object" && value !== null) {
186
191
  for (const [k, v] of Object.entries(value)) {
187
192
  def.set(tempBuf, k, v);