node-ctypes 2.2.0 → 2.3.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.
@@ -28,6 +28,7 @@
28
28
  */
29
29
 
30
30
  import { flush, mirrorsActive, refresh } from "./mirror.js";
31
+ import { copyInstance } from "../structures/helpers/common.js";
31
32
 
32
33
  /**
33
34
  * Factory che cattura le dipendenze in closure e restituisce un bundle di
@@ -67,8 +68,9 @@ export function createMemoryOps(deps) {
67
68
  if (type && typeof type === "object" && type._structDef !== undefined && typeof type._structDef.size === "number") {
68
69
  return type._structDef.size;
69
70
  }
70
- // Buffer, create_string_buffer() o istanza di array: dimensione in byte
71
- if (Buffer.isBuffer(type)) {
71
+ // Buffer, create_string_buffer(), istanza di array, TypedArray/DataView:
72
+ // dimensione in byte
73
+ if (Buffer.isBuffer(type) || ArrayBuffer.isView(type)) {
72
74
  return type.byteLength;
73
75
  }
74
76
  // Structure class
@@ -104,6 +106,31 @@ export function createMemoryOps(deps) {
104
106
  // es. gli argomenti POINTER dei callback passati a readValue/writeValue.
105
107
  const pointerTarget = (ptr) => (ptr._buffer !== null ? ptr._buffer : ptr.address);
106
108
 
109
+ // Memoria di readValue/writeValue: Buffer, istanza ctypes, puntatore,
110
+ // TypedArray/DataView o indirizzo (Buffer su `offset + size()` byte).
111
+ const memoryAt = (ptr, offset, size, name) => {
112
+ if (ptr !== null && typeof ptr === "object") {
113
+ if (ptr._pointerType !== undefined) {
114
+ ptr = pointerTarget(ptr);
115
+ } else if (Buffer.isBuffer(ptr._buffer)) {
116
+ ptr = ptr._buffer;
117
+ } else if (ArrayBuffer.isView(ptr) && !Buffer.isBuffer(ptr)) {
118
+ return Buffer.from(ptr.buffer, ptr.byteOffset, ptr.byteLength);
119
+ }
120
+ }
121
+ if (typeof ptr === "bigint" || typeof ptr === "number") {
122
+ if (!ptr) throw new TypeError(`${name}: NULL pointer`);
123
+ return ptrToBuffer(ptr, offset + size());
124
+ }
125
+ if (!Buffer.isBuffer(ptr)) throw new TypeError(`${name} requires a Buffer, a ctypes instance or a pointer address`);
126
+ return ptr;
127
+ };
128
+ const checkBounds = (ptr, offset, size, verb) => {
129
+ if (offset + size > ptr.length) {
130
+ throw new RangeError(`${verb} would exceed buffer bounds (offset: ${offset}, size: ${size}, buffer length: ${ptr.length})`);
131
+ }
132
+ };
133
+
107
134
  function readValue(ptr, type, offset = 0) {
108
135
  if (typeof offset !== "number" || offset < 0) {
109
136
  throw new RangeError("offset must be a non-negative number");
@@ -114,42 +141,32 @@ export function createMemoryOps(deps) {
114
141
 
115
142
  // SimpleCData class: usa _reader diretto
116
143
  if (typeof type === "function" && type._isSimpleCData) {
117
- if (Buffer.isBuffer(ptr)) {
118
- const size = type._size || sizeof(type);
119
- if (offset + size > ptr.length) {
120
- throw new RangeError(`Read would exceed buffer bounds (offset: ${offset}, size: ${size}, buffer length: ${ptr.length})`);
121
- }
122
- if (mirrorsActive) refresh(ptr, offset, size);
123
- return type._reader(ptr, offset);
124
- }
125
- if (typeof ptr === "bigint" || typeof ptr === "number") {
144
+ const size = type._size || sizeof(type);
145
+ if ((typeof ptr === "bigint" || typeof ptr === "number") && ptr !== 0n && ptr !== 0) {
126
146
  const nativeType = deps.nativeReadTypes !== undefined ? deps.nativeReadTypes.get(type) : undefined;
127
- if (nativeType !== undefined && ptr !== 0n && ptr !== 0) {
147
+ if (nativeType !== undefined) {
128
148
  return deps.native.readValue(ptr, nativeType, offset);
129
149
  }
130
- const size = type._size || sizeof(type);
131
- const buf = ptrToBuffer(ptr, size + offset);
132
- return type._reader(buf, offset);
133
150
  }
134
- throw new TypeError("readValue requires a Buffer or pointer address");
151
+ ptr = memoryAt(ptr, offset, () => size, "readValue");
152
+ checkBounds(ptr, offset, size, "Read");
153
+ if (mirrorsActive) refresh(ptr, offset, size);
154
+ return type._reader(ptr, offset);
135
155
  }
136
156
 
137
- // Structure class
157
+ let def;
138
158
  if (typeof type === "function" && type.prototype instanceof getStructure()) {
139
- const def = type._structDef || type._buildStruct();
140
- return def.toObject(ptr.subarray(offset, offset + def.size));
141
- }
142
- // Union class
143
- if (typeof type === "function" && type.prototype instanceof getUnion()) {
144
- const def = type._unionDef || type._buildUnion();
145
- return def.toObject(ptr.subarray(offset, offset + def.size));
146
- }
147
- // structDef / unionDef object
148
- if (typeof type === "object" && type !== null && type._isStructType && typeof type.toObject === "function") {
149
- return type.toObject(ptr.subarray(offset, offset + type.size));
150
- }
151
-
152
- throw new TypeError(`readValue: unsupported type ${type}`);
159
+ def = type._structDef || type._buildStruct();
160
+ } else if (typeof type === "function" && type.prototype instanceof getUnion()) {
161
+ def = type._unionDef || type._buildUnion();
162
+ } else if (typeof type === "object" && type !== null && type._isStructType && typeof type.toObject === "function") {
163
+ def = type;
164
+ } else {
165
+ throw new TypeError(`readValue: unsupported type ${type}`);
166
+ }
167
+ ptr = memoryAt(ptr, offset, () => def.size, "readValue");
168
+ checkBounds(ptr, offset, def.size, "Read");
169
+ return def.toObject(ptr.subarray(offset, offset + def.size));
153
170
  }
154
171
 
155
172
  /**
@@ -159,22 +176,12 @@ export function createMemoryOps(deps) {
159
176
  if (typeof offset !== "number" || offset < 0) {
160
177
  throw new RangeError("offset must be a non-negative number");
161
178
  }
162
- if (ptr !== null && typeof ptr === "object" && ptr._pointerType !== undefined) {
163
- ptr = pointerTarget(ptr);
164
- if (typeof ptr === "bigint") {
165
- ptr = ptrToBuffer(ptr, offset + sizeof(type));
166
- }
167
- }
179
+ ptr = memoryAt(ptr, offset, () => sizeof(type), "writeValue");
168
180
 
169
181
  // SimpleCData class: usa _writer diretto
170
182
  if (typeof type === "function" && type._isSimpleCData) {
171
- if (!Buffer.isBuffer(ptr)) {
172
- throw new TypeError("writeValue requires a Buffer");
173
- }
174
183
  const size = type._size || sizeof(type);
175
- if (offset + size > ptr.length) {
176
- throw new RangeError(`Write would exceed buffer bounds (offset: ${offset}, size: ${size}, buffer length: ${ptr.length})`);
177
- }
184
+ checkBounds(ptr, offset, size, "Write");
178
185
  type._writer(ptr, offset, value);
179
186
  if (mirrorsActive) flush(ptr, offset, size);
180
187
  return type._size;
@@ -183,10 +190,15 @@ export function createMemoryOps(deps) {
183
190
  // Structure/Union class o def — tutti gestiti con la stessa logica:
184
191
  // o value è un Buffer (copia raw) o è un object (set field-by-field).
185
192
  const writeComposite = (def) => {
193
+ checkBounds(ptr, offset, def.size, "Write");
186
194
  const tempBuf = ptr.subarray(offset, offset + def.size);
187
195
  if (Buffer.isBuffer(value)) {
188
196
  value.copy(tempBuf, 0, 0, def.size);
189
197
  if (mirrorsActive) flush(tempBuf);
198
+ } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
199
+ // Istanza struct/union: copia dei byte (Python), non campo per campo.
200
+ copyInstance(tempBuf, 0, def.size, value);
201
+ if (mirrorsActive) flush(tempBuf);
190
202
  } else if (typeof value === "object" && value !== null) {
191
203
  for (const [k, v] of Object.entries(value)) {
192
204
  def.set(tempBuf, k, v);
@@ -26,7 +26,7 @@
26
26
  * ```
27
27
  */
28
28
 
29
- import { writePointerField } from "../structures/helpers/common.js";
29
+ import { keepAlive, writePointerField } from "../structures/helpers/common.js";
30
30
  import { flush, mirrorAddress, mirrorsActive } from "./mirror.js";
31
31
 
32
32
  /**
@@ -56,6 +56,11 @@ import { flush, mirrorAddress, mirrorsActive } from "./mirror.js";
56
56
  * ```
57
57
  */
58
58
  export function addressOf(ptr, alloc, native) {
59
+ // Puntatore: l'indirizzo del puntatore stesso (Python addressof(p)), non
60
+ // quello della memoria puntata.
61
+ if (ptr && typeof ptr === "object" && ptr._pointerType !== undefined) {
62
+ ptr = ptr._pointerSlot;
63
+ }
59
64
  // Object wrapper (SimpleCData, Structure, Union, array proxy) → unwrap al Buffer.
60
65
  // Le istanze di array sono Proxy su un Buffer: Buffer.isBuffer() è vero in JS
61
66
  // ma il nativo non vede un Buffer, quindi si usa sempre `_buffer` se presente.
@@ -122,6 +127,11 @@ export function addressOf(ptr, alloc, native) {
122
127
  * ```
123
128
  */
124
129
  export function byref(obj) {
130
+ // Puntatore: la memoria del puntatore (T**), così una funzione C può
131
+ // scriverci un indirizzo e ri-puntarlo (Python byref(p)).
132
+ if (obj && typeof obj === "object" && obj._pointerType !== undefined) {
133
+ return obj._pointerSlot;
134
+ }
125
135
  // SimpleCData instance or Structure instance - return its buffer
126
136
  if (obj && obj._buffer && Buffer.isBuffer(obj._buffer)) {
127
137
  return obj._buffer;
@@ -194,15 +204,16 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
194
204
  if (ptr._buffer) {
195
205
  return targetType.fromBuffer(ptr._buffer);
196
206
  }
197
- return targetType.fromAddress(ptr.address);
207
+ return targetType.fromAddress(ptr.address, ptr);
198
208
  }
199
209
 
200
210
  // ctypes object with _buffer — distinguish data objects from pointer-value objects
201
211
  // Note: array proxies are Buffer.isBuffer()==true but also have ._buffer, so don't exclude Buffers
202
212
  if (ptr && typeof ptr === "object" && ptr._buffer && Buffer.isBuffer(ptr._buffer)) {
203
- // SimpleCData storing a pointer/address value (c_void_p, c_char_p, etc.)
204
- // → read the stored address value from the buffer
205
- if (ptr.constructor && ptr.constructor._isSimpleCData && ptr.constructor._type === native.CType.POINTER) {
213
+ // SimpleCData storing a pointer/address value (c_void_p, c_char_p,
214
+ // c_wchar_p) → read the stored address value from the buffer
215
+ const pointerValued = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
216
+ if (ptr.constructor && ptr.constructor._isSimpleCData && pointerValued.has(ptr.constructor._type)) {
206
217
  // This is a pointer-valued SimpleCData — read address from buffer
207
218
  const buf = ptr._buffer;
208
219
  let addr;
@@ -213,7 +224,8 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
213
224
  } else {
214
225
  throw new TypeError("cast(): buffer too small to contain a pointer");
215
226
  }
216
- return targetType.fromAddress(addr);
227
+ // Python: il risultato tiene viva la sorgente (la stringa di un c_char_p).
228
+ return targetType.fromAddress(addr, ptr);
217
229
  }
218
230
  // Array, Structure, Union — pointer to their data buffer
219
231
  // Python: cast(arr, POINTER(c_int32)) points to arr's memory
@@ -242,6 +254,15 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
242
254
  return targetType.fromAddress(addr);
243
255
  }
244
256
 
257
+ // c_void_p / c_char_p / c_wchar_p: an instance pointing to the source,
258
+ // which it keeps alive (Python: cast(buf, c_void_p).value == addressof(buf)).
259
+ if (typeof targetType === "function" && targetType._isSimpleCData === true && isPointerValued(targetType, native)) {
260
+ const result = new targetType();
261
+ writePointerField(result._buffer, 0, castSourceAddress(ptr, native), native.POINTER_SIZE);
262
+ if (typeof ptr === "object") keepAlive(result._buffer, 0, ptr);
263
+ return result;
264
+ }
265
+
245
266
  // Struct type - return wrapper object
246
267
  if (typeof targetType === "object" && targetType.size !== undefined) {
247
268
  const buf = Buffer.isBuffer(ptr) ? ptr : ptrToBuffer(ptr, targetType.size);
@@ -270,6 +291,28 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
270
291
  return readValue(tempBuf, targetType, 0);
271
292
  }
272
293
 
294
+ function isPointerValued(type, native) {
295
+ return type._type === native.CType.POINTER || type._type === native.CType.STRING || type._type === native.CType.WSTRING;
296
+ }
297
+
298
+ // Address given by a cast() source, as Python's c_void_p.from_param: the value
299
+ // of pointers, c_void_p, c_char_p and c_wchar_p, the memory of the others.
300
+ function castSourceAddress(ptr, native) {
301
+ if (typeof ptr === "bigint") return ptr;
302
+ if (typeof ptr === "number") return BigInt(ptr);
303
+ if (ptr !== null && typeof ptr === "object") {
304
+ if (ptr._pointerType !== undefined) return ptr.address;
305
+ const T = ptr.constructor;
306
+ if (T?._isSimpleCData === true && isPointerValued(T, native)) {
307
+ return native.POINTER_SIZE === 8 ? ptr._buffer.readBigUInt64LE(0) : BigInt(ptr._buffer.readUInt32LE(0));
308
+ }
309
+ if (Buffer.isBuffer(ptr._buffer)) return addressOf(ptr._buffer, null, native);
310
+ if (Buffer.isBuffer(ptr)) return addressOf(ptr, null, native);
311
+ if (ptr._as_parameter_ !== undefined) return castSourceAddress(ptr._as_parameter_, native);
312
+ }
313
+ throw new TypeError("cast(): ptr must be a BigInt, number, Buffer, ctypes instance, or PointerInstance");
314
+ }
315
+
273
316
  /**
274
317
  * Buffer over the memory at an address, used by `from_address`, `cast` and
275
318
  * pointers (not exported: the public, Python-compatible way is
@@ -407,8 +450,10 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
407
450
 
408
451
  // Python: per tipi semplici e Structure/Union `contents` (e p[i] per le struct)
409
452
  // è un'istanza viva sulla memoria puntata, non una copia del valore.
410
- const hasInstances = () => typeof baseType === "function" && (baseType._isSimpleCData === true || typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function");
411
- const isStructBase = () => typeof baseType === "function" && (typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function");
453
+ // Array (Python POINTER(c_int * 3)): contents e p[i] sono istanze dell'array.
454
+ const isArrayBase = () => baseType !== null && (typeof baseType === "function" || typeof baseType === "object") && baseType._isArrayType === true;
455
+ const hasInstances = () => isArrayBase() || (typeof baseType === "function" && (baseType._isSimpleCData === true || typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function"));
456
+ const isStructBase = () => isArrayBase() || (typeof baseType === "function" && (typeof baseType._buildStruct === "function" || typeof baseType._buildUnion === "function"));
412
457
 
413
458
  // POINTER(POINTER(T)) / POINTER(CFUNCTYPE): elementi puntatore, letti come
414
459
  // oggetto puntatore / funzione (NULL → null) e scritti come indirizzo.
@@ -470,13 +515,37 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
470
515
  * Creates a pointer instance with Python ctypes-compatible API.
471
516
  * Supports .contents property and [index] access for pointer arithmetic.
472
517
  */
473
- function createPointerInstance(addressOrBuffer) {
518
+ function createPointerInstance(addressOrBuffer, keep) {
474
519
  // Risolvi il thunk lazy alla prima creazione di istanza: a questo
475
520
  // punto la classe target è sicuramente inizializzata.
476
521
  resolveIfLazy();
477
522
 
478
523
  let _address = 0n;
479
524
  let _buffer = null;
525
+ // Python `_objects`: ciò che deve restare vivo finché il puntatore punta
526
+ // lì (la sorgente di cast(), il puntatore da cui deriva add()).
527
+ let _objects = keep;
528
+ // Memoria del puntatore (Python: un puntatore è un oggetto ctypes di
529
+ // POINTER_SIZE byte), creata alla prima richiesta di byref(p) /
530
+ // addressof(p). Da allora è lei a dare l'indirizzo: una funzione C che ci
531
+ // scrive (f(byref(p))) ri-punta p.
532
+ let _slot = null;
533
+
534
+ function sync() {
535
+ if (_slot === null) return;
536
+ const addr = native.POINTER_SIZE === 8 ? _slot.readBigUInt64LE(0) : BigInt(_slot.readUInt32LE(0));
537
+ if (addr !== _address) {
538
+ _address = addr;
539
+ _buffer = null;
540
+ _objects = undefined;
541
+ }
542
+ }
543
+
544
+ function store() {
545
+ if (_slot === null) return;
546
+ if (native.POINTER_SIZE === 8) _slot.writeBigUInt64LE(BigInt.asUintN(64, _address), 0);
547
+ else _slot.writeUInt32LE(Number(BigInt.asUintN(32, _address)), 0);
548
+ }
480
549
 
481
550
  if (addressOrBuffer === undefined || addressOrBuffer === null) {
482
551
  _address = 0n;
@@ -484,6 +553,9 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
484
553
  _address = addressOrBuffer;
485
554
  } else if (typeof addressOrBuffer === "number") {
486
555
  _address = BigInt(addressOrBuffer);
556
+ } else if (typeof addressOrBuffer === "object" && Buffer.isBuffer(addressOrBuffer._buffer)) {
557
+ // Istanza ctypes (array, struct): la sua memoria.
558
+ pointTo(addressOrBuffer._buffer);
487
559
  } else if (Buffer.isBuffer(addressOrBuffer)) {
488
560
  pointTo(addressOrBuffer);
489
561
  }
@@ -491,14 +563,17 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
491
563
  // Puntare a un Buffer; una copia di memoria nativa (memory/mirror.js)
492
564
  // vale il suo indirizzo originale, come un puntatore creato da indirizzo.
493
565
  function pointTo(buf) {
566
+ _objects = undefined;
494
567
  const mirrored = mirrorAddress(buf);
495
568
  if (mirrored !== undefined) {
496
569
  _buffer = null;
497
570
  _address = mirrored;
498
- return;
571
+ _objects = buf;
572
+ } else {
573
+ _buffer = buf;
574
+ _address = getBufferAddress(buf);
499
575
  }
500
- _buffer = buf;
501
- _address = getBufferAddress(buf);
576
+ store();
502
577
  }
503
578
 
504
579
  const instance = {
@@ -510,9 +585,27 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
510
585
  * Get the raw address as BigInt
511
586
  */
512
587
  get address() {
588
+ sync();
513
589
  return _address;
514
590
  },
515
591
 
592
+ /**
593
+ * Memoria del puntatore (POINTER_SIZE byte con l'indirizzo): ciò che
594
+ * byref(p) / addressof(p) passano al C.
595
+ */
596
+ get _pointerSlot() {
597
+ if (_slot === null) {
598
+ _slot = alloc(native.POINTER_SIZE);
599
+ store();
600
+ }
601
+ return _slot;
602
+ },
603
+
604
+ /** Oggetti tenuti vivi dal puntatore (Python `_objects`). */
605
+ get _objects() {
606
+ return _objects;
607
+ },
608
+
516
609
  /**
517
610
  * Python ctypes compatible: the pointed object. For simple types and
518
611
  * Structure/Union classes it is a live instance on the pointed memory
@@ -520,6 +613,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
520
613
  * the pointer to it, assigning a plain value writes it.
521
614
  */
522
615
  get contents() {
616
+ sync();
523
617
  if (_address === 0n && !_buffer) {
524
618
  throw new Error("NULL pointer access");
525
619
  }
@@ -537,8 +631,14 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
537
631
  },
538
632
 
539
633
  set contents(value) {
634
+ sync();
540
635
  // Python: assegnare un'istanza ri-punta il puntatore a quell'istanza.
541
- if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined) && Buffer.isBuffer(value._buffer)) {
636
+ if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined || value._arrayType !== undefined) && Buffer.isBuffer(value._buffer)) {
637
+ // Python accetta anche un'istanza di un altro tipo; una più piccola
638
+ // del tipo puntato farebbe leggere e scrivere oltre la sua memoria.
639
+ if (value._buffer.length < baseSize) {
640
+ throw new TypeError(`contents: ${value.constructor?.name ?? "instance"} (${value._buffer.length} bytes) is smaller than the pointed type (${baseSize} bytes)`);
641
+ }
542
642
  pointTo(value._buffer);
543
643
  return;
544
644
  }
@@ -558,6 +658,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
558
658
  * Returns the buffer this pointer points to (if available)
559
659
  */
560
660
  get _buffer() {
661
+ sync();
561
662
  return _buffer;
562
663
  },
563
664
 
@@ -574,12 +675,11 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
574
675
  set(value) {
575
676
  if (Buffer.isBuffer(value)) {
576
677
  pointTo(value);
577
- } else if (typeof value === "bigint") {
578
- _address = value;
579
- _buffer = null;
580
- } else if (typeof value === "number") {
678
+ } else if (typeof value === "bigint" || typeof value === "number") {
581
679
  _address = BigInt(value);
582
680
  _buffer = null;
681
+ _objects = undefined;
682
+ store();
583
683
  }
584
684
  },
585
685
 
@@ -587,6 +687,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
587
687
  * Check if pointer is NULL
588
688
  */
589
689
  get isNull() {
690
+ sync();
590
691
  return _address === 0n && !_buffer;
591
692
  },
592
693
 
@@ -600,6 +701,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
600
701
  },
601
702
 
602
703
  toString() {
704
+ sync();
603
705
  return `<${typeName} pointer at 0x${_address.toString(16)}>`;
604
706
  },
605
707
 
@@ -608,8 +710,10 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
608
710
  * `ptr + n`. The pointer keeps the same element type.
609
711
  */
610
712
  add(n) {
713
+ sync();
611
714
  const offsetBytes = BigInt(n) * BigInt(baseSize);
612
- return PointerType.fromAddress(_address + offsetBytes);
715
+ // Il nuovo puntatore tiene viva la memoria di questo (Python _objects).
716
+ return createPointerInstance(_address + offsetBytes, _buffer ?? _objects);
613
717
  },
614
718
 
615
719
  /**
@@ -717,8 +821,8 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
717
821
  * @param {bigint|number} address - Memory address
718
822
  * @returns {Object} Pointer instance
719
823
  */
720
- fromAddress(address) {
721
- return createPointerInstance(typeof address === "bigint" ? address : BigInt(address));
824
+ fromAddress(address, keep) {
825
+ return createPointerInstance(typeof address === "bigint" ? address : BigInt(address), keep);
722
826
  },
723
827
 
724
828
  /**
@@ -783,14 +887,16 @@ export function pointer(obj, POINTER_fn, sizeof, alloc, readValue, writeValue, c
783
887
  let targetBuffer;
784
888
  let baseType;
785
889
 
786
- if (Buffer.isBuffer(obj)) {
787
- targetBuffer = obj;
788
- baseType = c_void_p; // Generic pointer
789
- } else if (obj && obj._buffer) {
790
- // Structure/Union instance or SimpleCData with _buffer
890
+ // Le istanze di array sono Proxy su un Buffer (Buffer.isBuffer è vero): la
891
+ // loro memoria è `_buffer`, controllato per primo.
892
+ if (obj !== null && typeof obj === "object" && Buffer.isBuffer(obj._buffer)) {
893
+ // Structure/Union instance, array or SimpleCData with _buffer
791
894
  targetBuffer = obj._buffer;
792
895
  // Get the base type for POINTER creation
793
- if (obj.constructor && obj.constructor._type) {
896
+ if (obj._arrayType !== undefined) {
897
+ // Python: pointer(c_int * 3 instance) è un POINTER(c_int * 3).
898
+ baseType = obj._arrayType;
899
+ } else if (obj.constructor && obj.constructor._type) {
794
900
  // SimpleCData instance - use the class itself (c_int32, c_double, etc.)
795
901
  baseType = obj.constructor;
796
902
  } else if (obj._structDef) {
@@ -799,6 +905,9 @@ export function pointer(obj, POINTER_fn, sizeof, alloc, readValue, writeValue, c
799
905
  } else {
800
906
  baseType = c_void_p;
801
907
  }
908
+ } else if (Buffer.isBuffer(obj)) {
909
+ targetBuffer = obj;
910
+ baseType = c_void_p; // Generic pointer
802
911
  } else {
803
912
  throw new TypeError("pointer() argument must be a ctypes instance or Buffer");
804
913
  }
@@ -11,7 +11,6 @@
11
11
  * console.log(`Wide char size: ${WCHAR_SIZE} bytes`);
12
12
  */
13
13
 
14
- import { createRequire } from "node:module";
15
14
  import path from "node:path";
16
15
 
17
16
  /**
@@ -114,13 +114,57 @@ export function FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
114
114
  * @param {Object} c_void_p - c_void_p type reference
115
115
  * @returns {Error} Error with `.winerror = code` and a formatted message
116
116
  */
117
- export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
118
- const msg = FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
117
+ export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p, descr) {
118
+ const msg = descr ?? FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
119
119
  const err = new Error(`[WinError ${code}] ${msg}`);
120
+ // Python: OSError(None, descr, None, code) — errno derivato da winerror.
120
121
  err.winerror = code;
122
+ err.errno = winerrorToErrno(code);
123
+ err.strerror = msg;
121
124
  return err;
122
125
  }
123
126
 
127
+ // errno (valori del CRT Microsoft) di un codice Windows, come
128
+ // winerror_to_errno di CPython (PC/errmap.h).
129
+ const ENOENT = 2;
130
+ const errnoGroups = [
131
+ [ENOENT, [2, 3, 15, 18, 53, 67, 161, 206]],
132
+ [7, [10]], // E2BIG
133
+ [8, [11, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202]], // ENOEXEC
134
+ [9, [6, 114, 130]], // EBADF
135
+ [10, [128, 129]], // ECHILD
136
+ [11, [89, 164, 215]], // EAGAIN
137
+ [12, [7, 8, 9, 1816]], // ENOMEM
138
+ [13, [5, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 65, 82, 83, 108, 132, 158, 167]], // EACCES
139
+ [17, [80, 183]], // EEXIST
140
+ [18, [17]], // EXDEV
141
+ [20, [267]], // ENOTDIR
142
+ [24, [4]], // EMFILE
143
+ [28, [112]], // ENOSPC
144
+ [32, [109, 232]], // EPIPE
145
+ [41, [145]], // ENOTEMPTY
146
+ [42, [1113]], // EILSEQ
147
+ [138, [258]], // ETIMEDOUT
148
+ ];
149
+ const errnoByWinerror = new Map(errnoGroups.flatMap(([errno, codes]) => codes.map((code) => [code, errno])));
150
+ const EINVAL = 22;
151
+
152
+ /**
153
+ * errno of a Windows error code (CPython `winerror_to_errno`).
154
+ *
155
+ * @param {number} winerror - Windows error code (or FACILITY_WIN32 HRESULT)
156
+ * @returns {number} errno value
157
+ */
158
+ export function winerrorToErrno(winerror) {
159
+ let code = winerror >>> 0;
160
+ if ((code & 0xffff0000) >>> 0 === 0x80070000) code &= 0xffff;
161
+ if (code >= 10000 && code < 12000) {
162
+ // Winsock: i codici sono già errno (alcuni con offset 10000).
163
+ return [10004, 10009, 10013, 10014, 10022, 10024].includes(code) ? code - 10000 : code;
164
+ }
165
+ return errnoByWinerror.get(code) ?? EINVAL;
166
+ }
167
+
124
168
  /**
125
169
  * Raised when a foreign function call cannot convert one of the passed
126
170
  * arguments (Python ctypes `ctypes.ArgumentError`). Subclass of `TypeError`.
@@ -135,8 +179,8 @@ export function WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p) {
135
179
  * ```
136
180
  */
137
181
  export class ArgumentError extends TypeError {
138
- constructor(message) {
139
- super(message);
182
+ constructor(message, options) {
183
+ super(message, options);
140
184
  this.name = "ArgumentError";
141
185
  }
142
186
  }