node-ctypes 2.1.1 → 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.
@@ -27,6 +27,7 @@
27
27
  */
28
28
 
29
29
  import { writePointerField } from "../structures/helpers/common.js";
30
+ import { flush, mirrorAddress, mirrorsActive } from "./mirror.js";
30
31
 
31
32
  /**
32
33
  * Gets the memory address of a buffer or pointer.
@@ -270,33 +271,16 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
270
271
  }
271
272
 
272
273
  /**
273
- * Creates a buffer backed by a specific memory address.
274
- *
275
- * **WARNING**: This is a low-level operation! Accessing invalid memory will
276
- * crash the process. Only use with addresses from trusted sources (FFI returns,
277
- * addressOf, etc.).
274
+ * Buffer over the memory at an address, used by `from_address`, `cast` and
275
+ * pointers (not exported: the public, Python-compatible way is
276
+ * `array(c_uint8, n).from_address(address)`). Where external buffers are not
277
+ * allowed it is a synchronized copy (see memory/mirror.js).
278
278
  *
279
279
  * @param {bigint|number} address - Memory address
280
280
  * @param {number} size - Size in bytes
281
281
  * @param {Object} native - Native module reference
282
- * @returns {Buffer} Buffer pointing to the address
283
- *
284
- * @example Read C string from pointer
285
- * ```javascript
286
- * import { ptrToBuffer } from 'node-ctypes';
287
- *
288
- * // Got pointer from C function
289
- * const str_ptr = some_c_function(); // Returns pointer
290
- * const buf = ptrToBuffer(str_ptr, 256);
291
- * const str = buf.toString('utf8');
292
- * ```
293
- *
294
- * @example Access struct at address
295
- * ```javascript
296
- * const addr = get_struct_ptr(); // From C
297
- * const buf = ptrToBuffer(addr, sizeof(MyStruct));
298
- * const struct_data = MyStruct.toObject(buf);
299
- * ```
282
+ * @returns {Buffer|null} Buffer over the address, `null` for NULL
283
+ * @private
300
284
  */
301
285
  export function ptrToBuffer(address, size, native) {
302
286
  return native.ptrToBuffer(address, size);
@@ -440,8 +424,13 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
440
424
  }
441
425
 
442
426
  function writePointerAt(buffer, address, offset, value) {
443
- const inBuffer = buffer && offset + baseSize <= buffer.length;
444
- writePointerField(inBuffer ? buffer : native.ptrToBuffer(address + BigInt(offset), baseSize), inBuffer ? offset : 0, value, baseSize);
427
+ if (buffer && offset + baseSize <= buffer.length) {
428
+ writePointerField(buffer, offset, value, baseSize);
429
+ return;
430
+ }
431
+ const target = native.ptrToBuffer(address + BigInt(offset), baseSize);
432
+ writePointerField(target, 0, value, baseSize);
433
+ if (mirrorsActive) flush(target);
445
434
  }
446
435
 
447
436
  function instanceAt(buffer, address, offset) {
@@ -451,6 +440,22 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
451
440
  return baseType.from_address(address + BigInt(offset));
452
441
  }
453
442
 
443
+ // Scrittura a un indirizzo senza Buffer associato: per le primitive il
444
+ // valore va in un Buffer V8 (uno per tipo puntatore, riusato) e il nativo
445
+ // lo copia all'indirizzo, invece di creare un Buffer esterno (~400 ns,
446
+ // vietato in Electron).
447
+ let scratch = null;
448
+ function writeAtAddress(addr, value) {
449
+ if (typeof baseType === "function" && baseType._isSimpleCData) {
450
+ scratch ??= alloc(baseSize);
451
+ baseType._writer(scratch, 0, value);
452
+ native.writeMemory(scratch, 0, baseSize, addr);
453
+ return;
454
+ }
455
+ const buf = native.ptrToBuffer(addr, baseSize);
456
+ writeValue(buf, baseType, value, 0);
457
+ }
458
+
454
459
  // Lettura a un indirizzo senza Buffer associato: per le primitive
455
460
  // readValue(indirizzo) evita il Buffer esterno di ptrToBuffer.
456
461
  function readAtAddress(addr) {
@@ -480,9 +485,20 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
480
485
  } else if (typeof addressOrBuffer === "number") {
481
486
  _address = BigInt(addressOrBuffer);
482
487
  } else if (Buffer.isBuffer(addressOrBuffer)) {
483
- // This is a buffer we're pointing TO
484
- _buffer = addressOrBuffer;
485
- _address = getBufferAddress(addressOrBuffer);
488
+ pointTo(addressOrBuffer);
489
+ }
490
+
491
+ // Puntare a un Buffer; una copia di memoria nativa (memory/mirror.js)
492
+ // vale il suo indirizzo originale, come un puntatore creato da indirizzo.
493
+ function pointTo(buf) {
494
+ const mirrored = mirrorAddress(buf);
495
+ if (mirrored !== undefined) {
496
+ _buffer = null;
497
+ _address = mirrored;
498
+ return;
499
+ }
500
+ _buffer = buf;
501
+ _address = getBufferAddress(buf);
486
502
  }
487
503
 
488
504
  const instance = {
@@ -523,8 +539,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
523
539
  set contents(value) {
524
540
  // Python: assegnare un'istanza ri-punta il puntatore a quell'istanza.
525
541
  if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined) && Buffer.isBuffer(value._buffer)) {
526
- _buffer = value._buffer;
527
- _address = getBufferAddress(value._buffer);
542
+ pointTo(value._buffer);
528
543
  return;
529
544
  }
530
545
  if (_address === 0n && !_buffer) {
@@ -535,8 +550,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
535
550
  } else if (_buffer) {
536
551
  writeValue(_buffer, baseType, value, 0);
537
552
  } else {
538
- const buf = native.ptrToBuffer(_address, baseSize);
539
- writeValue(buf, baseType, value, 0);
553
+ writeAtAddress(_address, value);
540
554
  }
541
555
  },
542
556
 
@@ -559,8 +573,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
559
573
  */
560
574
  set(value) {
561
575
  if (Buffer.isBuffer(value)) {
562
- _buffer = value;
563
- _address = getBufferAddress(value);
576
+ pointTo(value);
564
577
  } else if (typeof value === "bigint") {
565
578
  _address = value;
566
579
  _buffer = null;
@@ -656,10 +669,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
656
669
  writeValue(_buffer, baseType, value, offset);
657
670
  return true;
658
671
  }
659
- // Use native to write at address + offset
660
- const addr = _address + BigInt(offset);
661
- const buf = native.ptrToBuffer(addr, baseSize);
662
- writeValue(buf, baseType, value, 0);
672
+ writeAtAddress(_address + BigInt(offset), value);
663
673
  return true;
664
674
  }
665
675
  return Reflect.set(target, prop, value, receiver);
@@ -64,6 +64,8 @@
64
64
  * ```
65
65
  */
66
66
 
67
+ import { kMirrorBase, mirrorBase, mirroredAccessors, mirrorsActive } from "../memory/mirror.js";
68
+
67
69
  /**
68
70
  * Creates the Structure base class with required dependencies injected.
69
71
  *
@@ -81,9 +83,13 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
81
83
  // Un handler Proxy per definizione, condiviso da tutte le istanze: prima
82
84
  // ogni `new` ricreava l'handler (5 closure) e la mappa dei nomi dei campi.
83
85
  const handlerCache = new WeakMap();
86
+ // Istanze su una copia di memoria nativa (Electron, memory/mirror.js):
87
+ // stesso handler con lettori e scrittori che sincronizzano il campo.
88
+ const mirroredHandlerCache = new WeakMap();
84
89
 
85
- function getProxyHandler(def) {
86
- let handler = handlerCache.get(def);
90
+ function getProxyHandler(def, mirrored = false) {
91
+ const cache = mirrored ? mirroredHandlerCache : handlerCache;
92
+ let handler = cache.get(def);
87
93
  if (handler !== undefined) return handler;
88
94
 
89
95
  // Lookup plana dei nomi (normali + sotto-campi anonymous) su oggetto
@@ -101,8 +107,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
101
107
 
102
108
  // Pre-compiled reader/writer maps from structDef for FAST PATH
103
109
  // (avoids going through def.get/def.set branching on every access)
104
- const readers = def.fieldReaders;
105
- const writers = def.fieldWriters;
110
+ const { fieldReaders: readers, fieldWriters: writers } = mirrored ? mirroredAccessors(def) : def;
106
111
 
107
112
  handler = {
108
113
  get(target, prop, receiver) {
@@ -111,7 +116,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
111
116
  // una Union (unionDef non espone fieldReaders al livello esterno).
112
117
  if (typeof prop === "string") {
113
118
  const reader = readers !== undefined ? readers[prop] : undefined;
114
- if (reader !== undefined) return reader(target[kBuffer]);
119
+ if (reader !== undefined) return reader(target[kBuffer], target[kMirrorBase]);
115
120
  if (allFieldNames[prop] === true) return def.get(target[kBuffer], prop);
116
121
  }
117
122
 
@@ -143,7 +148,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
143
148
  if (typeof prop === "string") {
144
149
  const writer = writers !== undefined ? writers[prop] : undefined;
145
150
  if (writer !== undefined) {
146
- writer(target[kBuffer], value);
151
+ writer(target[kBuffer], value, target[kMirrorBase]);
147
152
  return true;
148
153
  }
149
154
  if (allFieldNames[prop] === true) {
@@ -190,7 +195,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
190
195
  return Reflect.getOwnPropertyDescriptor(target, prop);
191
196
  },
192
197
  };
193
- handlerCache.set(def, handler);
198
+ cache.set(def, handler);
194
199
  return handler;
195
200
  }
196
201
 
@@ -317,8 +322,11 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
317
322
  this.__buffer = buf;
318
323
  this.__structDef = def;
319
324
  this[kBuffer] = buf;
325
+ // Indirizzo di una copia di memoria nativa (Electron), undefined altrimenti.
326
+ const base = mirrorsActive ? mirrorBase(buf) : undefined;
327
+ this[kMirrorBase] = base;
320
328
 
321
- return new Proxy(this, getProxyHandler(def));
329
+ return new Proxy(this, getProxyHandler(def, base !== undefined));
322
330
  }
323
331
 
324
332
  // Static getters for size, alignment, and fields (enables use as nested type)
@@ -106,6 +106,7 @@
106
106
  */
107
107
  import { encodeWide, decodeWide } from "../../memory/buffer.js";
108
108
  import { funcPtrFieldType, writePointerField } from "./common.js";
109
+ import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
109
110
 
110
111
  // Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
111
112
  // `.value` stringa fino al primo NUL; quelli di c_char anche `.raw` (bytes).
@@ -129,7 +130,7 @@ function setCharArrayValue(buf, charKind, wcharSize, value, message) {
129
130
  }
130
131
  }
131
132
 
132
- export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType) {
133
+ export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer) {
133
134
  // Validate elementType: accept SimpleCData classes, Structure/Union classes,
134
135
  // or native CType-like objects.
135
136
  const isSimple = typeof elementType === "function" && elementType._isSimpleCData;
@@ -194,6 +195,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
194
195
  if (bytes.length > buf.length) throw new RangeError("byte string too long");
195
196
  bytes.copy(buf);
196
197
  };
198
+ const getRaw = (buf) => Buffer.from(buf);
197
199
 
198
200
  // Elementi puntatore: NULL → null, altrimenti oggetto puntatore / funzione.
199
201
  const pointerElemType = !isPointerElem ? null : typeof elementType === "function" ? funcPtrFieldType(elementType) : elementType;
@@ -249,6 +251,43 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
249
251
  return false;
250
252
  };
251
253
 
254
+ // Array su una copia della memoria nativa (memory/mirror.js): un elemento
255
+ // scalare o puntatore si rilegge prima di leggerlo e si ricopia dopo averlo
256
+ // scritto (viene sovrascritto per intero). Gli elementi struct e array sono
257
+ // istanze che si sincronizzano da sole.
258
+ const scalarElem = !isStructElem && !isArrayElem;
259
+ const mirroredReadAt = (target, index) => {
260
+ if (scalarElem && index >= 0 && index < count) refresh(target, index * elementSize, elementSize);
261
+ return readAt(target, index);
262
+ };
263
+ const mirroredWriteAt = (target, index, value) => {
264
+ const result = writeAt(target, index, value);
265
+ if (result && (scalarElem || (isArrayElem && (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer))))) {
266
+ flush(target, index * elementSize, elementSize);
267
+ }
268
+ return result;
269
+ };
270
+ const synced =
271
+ (fn) =>
272
+ (buf, ...args) => {
273
+ refresh(buf);
274
+ const result = fn(buf, ...args);
275
+ flush(buf);
276
+ return result;
277
+ };
278
+ const mirroredGetValue =
279
+ getValue &&
280
+ ((buf) => {
281
+ refresh(buf);
282
+ return getValue(buf);
283
+ });
284
+ const mirroredSetValue = setValue && synced(setValue);
285
+ const mirroredSetRaw = synced(setRaw);
286
+ const mirroredGetRaw = (buf) => {
287
+ refresh(buf);
288
+ return Buffer.from(buf);
289
+ };
290
+
252
291
  // Indice da una chiave che inizia con una cifra (il caso comune arr[i]);
253
292
  // NaN per tutto il resto, che segue il percorso generico.
254
293
  const fastIndex = (prop) => {
@@ -262,109 +301,111 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
262
301
  return NaN;
263
302
  };
264
303
 
265
- // Wrap function that returns a Proxy for array-like indexing
266
- const wrap = function (buffer) {
267
- return new Proxy(buffer, {
268
- get(target, prop, receiver) {
269
- const fast = fastIndex(prop);
270
- if (fast === fast) {
271
- return readAt(target, fast);
272
- }
273
-
274
- if (charKind !== undefined) {
275
- if (prop === "value") return getValue(target);
276
- if (prop === "raw" && charKind === "char") return Buffer.from(target);
277
- }
278
-
279
- // Special case for _buffer to return the underlying buffer
280
- if (prop === "_buffer") {
281
- return target;
282
- }
304
+ // Proxy handler for array-like indexing: one per array type (and one for
305
+ // copies of native memory), the buffer is the target.
306
+ const makeHandler = (readAt, writeAt, getValue, setValue, setRaw, getRaw) => ({
307
+ get(target, prop, receiver) {
308
+ const fast = fastIndex(prop);
309
+ if (fast === fast) {
310
+ return readAt(target, fast);
311
+ }
283
312
 
284
- // Python ctypes parity: `len(arr)` ritorna il numero di elementi,
285
- // non la dimensione in byte del buffer. Senza questo trap,
286
- // `arr.length` casca sul buffer sottostante e ritorna byte count,
287
- // rompendo il pattern idiomatico `for (let i = 0; i < arr.length; i++)`.
288
- if (prop === "length") return count;
289
- if (prop === "byteLength") return target.length;
290
-
291
- // Special case for toString to show array contents
292
- if (prop === "toString") {
293
- return function () {
294
- try {
295
- const arr = Array.from(this);
296
- return `[${arr.join(", ")}]`;
297
- } catch (e) {
298
- return "[error]";
299
- }
300
- }.bind(receiver);
301
- }
313
+ if (charKind !== undefined) {
314
+ if (prop === "value") return getValue(target);
315
+ if (prop === "raw" && charKind === "char") return getRaw(target);
316
+ }
302
317
 
303
- // Intercept Symbol.iterator to iterate over elements, not bytes
304
- if (prop === Symbol.iterator) {
305
- return function* () {
306
- for (let i = 0; i < count; i++) {
307
- yield readAt(target, i);
308
- }
309
- };
310
- }
318
+ // Special case for _buffer to return the underlying buffer
319
+ if (prop === "_buffer") {
320
+ return target;
321
+ }
311
322
 
312
- // Ignore other Symbols
313
- if (typeof prop === "symbol") {
314
- const value = Reflect.get(target, prop, target);
315
- if (typeof value === "function") {
316
- return value.bind(target);
323
+ // Python ctypes parity: `len(arr)` ritorna il numero di elementi,
324
+ // non la dimensione in byte del buffer. Senza questo trap,
325
+ // `arr.length` casca sul buffer sottostante e ritorna byte count,
326
+ // rompendo il pattern idiomatico `for (let i = 0; i < arr.length; i++)`.
327
+ if (prop === "length") return count;
328
+ if (prop === "byteLength") return target.length;
329
+
330
+ // Special case for toString to show array contents
331
+ if (prop === "toString") {
332
+ return function () {
333
+ try {
334
+ const arr = Array.from(this);
335
+ return `[${arr.join(", ")}]`;
336
+ } catch (e) {
337
+ return "[error]";
317
338
  }
318
- return value;
319
- }
339
+ }.bind(receiver);
340
+ }
320
341
 
321
- // If it's a number (index) - intercept BEFORE checking target
322
- const index = Number(prop);
323
- if (Number.isInteger(index) && !isNaN(index)) {
324
- return readAt(target, index);
325
- }
342
+ // Intercept Symbol.iterator to iterate over elements, not bytes
343
+ if (prop === Symbol.iterator) {
344
+ return function* () {
345
+ for (let i = 0; i < count; i++) {
346
+ yield readAt(target, i);
347
+ }
348
+ };
349
+ }
326
350
 
327
- // For everything else, use the normal buffer
351
+ // Ignore other Symbols
352
+ if (typeof prop === "symbol") {
328
353
  const value = Reflect.get(target, prop, target);
329
- // If it's a function, bind it to the target
330
354
  if (typeof value === "function") {
331
355
  return value.bind(target);
332
356
  }
333
357
  return value;
334
- },
335
- set(target, prop, value) {
336
- const fast = fastIndex(prop);
337
- if (fast === fast) {
338
- return writeAt(target, fast, value);
339
- }
340
-
341
- if (charKind !== undefined) {
342
- if (prop === "value") {
343
- setValue(target, value);
344
- return true;
345
- }
346
- if (prop === "raw" && charKind === "char") {
347
- setRaw(target, value);
348
- return true;
349
- }
350
- }
358
+ }
351
359
 
352
- // Ignore Symbols
353
- if (typeof prop === "symbol") {
354
- return Reflect.set(target, prop, value, target);
355
- }
360
+ // If it's a number (index) - intercept BEFORE checking target
361
+ const index = Number(prop);
362
+ if (Number.isInteger(index) && !isNaN(index)) {
363
+ return readAt(target, index);
364
+ }
356
365
 
357
- // `length`/`byteLength` sono read-only (parity Python Array).
358
- if (prop === "length" || prop === "byteLength") return false;
366
+ // For everything else, use the normal buffer
367
+ const value = Reflect.get(target, prop, target);
368
+ // If it's a function, bind it to the target
369
+ if (typeof value === "function") {
370
+ return value.bind(target);
371
+ }
372
+ return value;
373
+ },
374
+ set(target, prop, value) {
375
+ const fast = fastIndex(prop);
376
+ if (fast === fast) {
377
+ return writeAt(target, fast, value);
378
+ }
359
379
 
360
- const index = Number(prop);
361
- if (Number.isInteger(index) && !isNaN(index)) {
362
- return writeAt(target, index, value);
380
+ if (charKind !== undefined) {
381
+ if (prop === "value") {
382
+ setValue(target, value);
383
+ return true;
384
+ }
385
+ if (prop === "raw" && charKind === "char") {
386
+ setRaw(target, value);
387
+ return true;
363
388
  }
389
+ }
390
+
391
+ // Ignore Symbols
392
+ if (typeof prop === "symbol") {
364
393
  return Reflect.set(target, prop, value, target);
365
- },
366
- });
367
- };
394
+ }
395
+
396
+ // `length`/`byteLength` sono read-only (parity Python Array).
397
+ if (prop === "length" || prop === "byteLength") return false;
398
+
399
+ const index = Number(prop);
400
+ if (Number.isInteger(index) && !isNaN(index)) {
401
+ return writeAt(target, index, value);
402
+ }
403
+ return Reflect.set(target, prop, value, target);
404
+ },
405
+ });
406
+ const handler = makeHandler(readAt, writeAt, getValue, setValue, setRaw, getRaw);
407
+ const mirroredHandler = mirrorsActive ? makeHandler(mirroredReadAt, mirroredWriteAt, mirroredGetValue, mirroredSetValue, mirroredSetRaw, mirroredGetRaw) : null;
408
+ const wrap = (buffer) => new Proxy(buffer, mirroredHandler !== null && isMirror(buffer) ? mirroredHandler : handler);
368
409
 
369
410
  // create automatically returns the proxy
370
411
  const create = (values) => {
@@ -381,6 +422,36 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
381
422
  return wrap(buffer);
382
423
  };
383
424
 
425
+ // Python: (c_int * 3).from_buffer / from_buffer_copy / from_address.
426
+ const byteSize = count * elementSize;
427
+ const bytesOf = (source, name) => {
428
+ const bytes = source !== null && typeof source === "object" && Buffer.isBuffer(source._buffer) ? source._buffer : source;
429
+ if (!(bytes instanceof Uint8Array)) throw new TypeError(`${name}: source must be a Buffer or a ctypes instance`);
430
+ return bytes;
431
+ };
432
+ const checkRange = (bytes, offset, name) => {
433
+ if (!Number.isInteger(offset) || offset < 0) throw new RangeError(`${name}: offset must be a non-negative integer`);
434
+ if (bytes.byteLength - offset < byteSize) throw new RangeError(`${name}: source too small (${bytes.byteLength - offset} < ${byteSize})`);
435
+ };
436
+ const from_buffer = (source, offset = 0) => {
437
+ const bytes = bytesOf(source, "from_buffer");
438
+ checkRange(bytes, offset, "from_buffer");
439
+ const view = Buffer.from(bytes.buffer, bytes.byteOffset + offset, byteSize);
440
+ return wrap(view);
441
+ };
442
+ const from_buffer_copy = (source, offset = 0) => {
443
+ const bytes = bytesOf(source, "from_buffer_copy");
444
+ checkRange(bytes, offset, "from_buffer_copy");
445
+ const copy = alloc(byteSize);
446
+ copy.set(bytes.subarray(offset, offset + byteSize));
447
+ return wrap(copy);
448
+ };
449
+ const from_address = (address) => {
450
+ if (!address) throw new TypeError("from_address: NULL address");
451
+ if (byteSize === 0) return wrap(alloc(0));
452
+ return wrap(ptrToBuffer(typeof address === "bigint" ? address : BigInt(address), byteSize));
453
+ };
454
+
384
455
  // Python: il tipo array si chiama con gli elementi, (c_int * 3)(1, 2, 3)
385
456
  // → array(c_int, 3)(1, 2, 3) (anche con `new`). `.create([...])` resta.
386
457
  const ArrayCType = function (...values) {
@@ -404,10 +475,15 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
404
475
  // Explicit wrap method
405
476
  wrap: { value: wrap, enumerable: true },
406
477
 
478
+ // Python ctypes: instances on existing memory
479
+ from_buffer: { value: from_buffer, enumerable: true },
480
+ from_buffer_copy: { value: from_buffer_copy, enumerable: true },
481
+ from_address: { value: from_address, enumerable: true },
482
+
407
483
  // Array di caratteri: tipo e conversione da/verso stringa (campi struct).
408
484
  _charKind: { value: charKind },
409
- getValue: { value: getValue },
410
- setValue: { value: setValue },
485
+ getValue: { value: mirrorsActive && getValue ? (buf) => (isMirror(buf) ? mirroredGetValue : getValue)(buf) : getValue },
486
+ setValue: { value: mirrorsActive && setValue ? (buf, ...args) => (isMirror(buf) ? mirroredSetValue : setValue)(buf, ...args) : setValue },
411
487
 
412
488
  // For compatibility, expose the native array (needed for StructType.addField)
413
489
  _native: { value: nativeArray },
@@ -35,6 +35,7 @@
35
35
 
36
36
  import { _readBitField, _writeBitField } from "./bitfield.js";
37
37
  import { buildWrapper } from "./wrap.js";
38
+ import { isMirror, syncDefinition } from "../../memory/mirror.js";
38
39
  import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
39
40
 
40
41
  /**
@@ -659,6 +660,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
659
660
  ? new Proxy(nestedBuf, buildWrapper(field.type, {
660
661
  instanceTag: "NestedStructInstance",
661
662
  exposeAnonymous: true,
663
+ mirrored: isMirror(nestedBuf),
662
664
  }))
663
665
  : field.type.toObject(nestedBuf);
664
666
  }
@@ -943,5 +945,5 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
943
945
  return this.toObject(this.create(values)._buffer);
944
946
  };
945
947
 
946
- return structDef;
948
+ return syncDefinition(structDef);
947
949
  }
@@ -36,6 +36,7 @@
36
36
 
37
37
  import { _readBitField, _writeBitField } from "./bitfield.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
+ import { syncDefinition } from "../../memory/mirror.js";
39
40
  import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
40
41
 
41
42
  /**
@@ -602,5 +603,5 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
602
603
  },
603
604
  };
604
605
 
605
- return unionDef;
606
+ return syncDefinition(unionDef);
606
607
  }
@@ -18,6 +18,8 @@
18
18
  * `!f.isAnonymous`) gestite inline in `union.js`.
19
19
  */
20
20
 
21
+ import { mirroredAccessors } from "../../memory/mirror.js";
22
+
21
23
  // Proprietà meta del Buffer che NON vanno mai interpretate come field name.
22
24
  // Per i campi Proxy passano direttamente attraverso al target buffer.
23
25
  const BUFFER_META_PROPS = new Set([
@@ -28,6 +30,10 @@ const BUFFER_META_PROPS = new Set([
28
30
  "BYTES_PER_ELEMENT",
29
31
  ]);
30
32
 
33
+ // L'handler dipende solo da def e opzioni (il Buffer è il target): uno per
34
+ // combinazione, invece di ricrearlo a ogni accesso a un campo annidato.
35
+ const wrapperCache = new WeakMap();
36
+
31
37
  /**
32
38
  * Costruisce un Proxy handler per un'istanza Structure/Union.
33
39
  *
@@ -45,10 +51,28 @@ const BUFFER_META_PROPS = new Set([
45
51
  * @param {string} opts.instanceTag — valore restituito per Symbol.toStringTag
46
52
  * @param {boolean} opts.exposeAnonymous — true per struct (sotto-campi `_anonymous_`
47
53
  * visibili come top-level), false per union.
54
+ * @param {boolean} [opts.mirrored] — Buffer copia di memoria nativa (Electron):
55
+ * lettori e scrittori che sincronizzano il campo.
48
56
  * @returns {ProxyHandler<Buffer>}
49
57
  */
50
- export function buildWrapper(def, { instanceTag, exposeAnonymous }) {
51
- const { fieldMap, fieldReaders, fieldWriters, anonymousFieldNames } = def;
58
+ export function buildWrapper(def, { instanceTag, exposeAnonymous, mirrored = false }) {
59
+ let byOptions = wrapperCache.get(def);
60
+ if (byOptions === undefined) {
61
+ byOptions = new Map();
62
+ wrapperCache.set(def, byOptions);
63
+ }
64
+ const key = `${instanceTag}|${exposeAnonymous}|${mirrored}`;
65
+ let handler = byOptions.get(key);
66
+ if (handler === undefined) {
67
+ handler = createWrapper(def, instanceTag, exposeAnonymous, mirrored);
68
+ byOptions.set(key, handler);
69
+ }
70
+ return handler;
71
+ }
72
+
73
+ function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
74
+ const { fieldMap, anonymousFieldNames } = def;
75
+ const { fieldReaders, fieldWriters } = mirrored ? mirroredAccessors(def) : def;
52
76
 
53
77
  // Precalcola la lista di chiavi visibili (stabile durante tutta la vita
54
78
  // del def). Evita di ricostruirla a ogni Object.keys / {...spread} / ecc.