node-ctypes 2.2.0 → 2.4.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +932 -0
  2. package/README.md +504 -99
  3. package/build/Release/ctypes-darwin-arm64.node +0 -0
  4. package/build/Release/ctypes-darwin-x64.node +0 -0
  5. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  6. package/build/Release/ctypes-linux-arm64.node +0 -0
  7. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  8. package/build/Release/ctypes-linux-x64.node +0 -0
  9. package/build/Release/ctypes-win32-arm64.node +0 -0
  10. package/build/Release/ctypes-win32-x64.node +0 -0
  11. package/lib/core/Library.js +136 -109
  12. package/lib/core/callback.js +17 -20
  13. package/lib/core/conversions.js +376 -16
  14. package/lib/core/funcptr.js +148 -73
  15. package/lib/core/lazy-loader.js +10 -4
  16. package/lib/core/types.js +201 -98
  17. package/lib/index.d.ts +276 -83
  18. package/lib/index.js +44 -32
  19. package/lib/memory/buffer.js +82 -22
  20. package/lib/memory/operations.js +55 -45
  21. package/lib/memory/pointer.js +233 -57
  22. package/lib/platform/constants.js +0 -1
  23. package/lib/platform/errors.js +48 -4
  24. package/lib/platform/find_library.js +78 -19
  25. package/lib/platform/win_types.js +8 -3
  26. package/lib/structures/Structure.js +252 -203
  27. package/lib/structures/Union.js +10 -21
  28. package/lib/structures/helpers/array.js +102 -16
  29. package/lib/structures/helpers/bitfield.js +75 -150
  30. package/lib/structures/helpers/common.js +310 -21
  31. package/lib/structures/helpers/layout.js +145 -0
  32. package/lib/structures/helpers/struct.js +160 -419
  33. package/lib/structures/helpers/union.js +154 -155
  34. package/lib/structures/helpers/wrap.js +3 -15
  35. package/lib/types/SimpleCData.js +11 -32
  36. package/lib/types/primitives.js +160 -113
  37. package/lib/utils/cache.js +34 -2
  38. package/package.json +4 -1
package/lib/index.js CHANGED
@@ -20,7 +20,7 @@ import path from "node:path";
20
20
  import { fileURLToPath } from "node:url";
21
21
 
22
22
  // Import refactored modules
23
- import { LRUCache } from "./utils/cache.js";
23
+ import { LRUCache, cacheWeakValue } from "./utils/cache.js";
24
24
  import { _initConstants } from "./platform/constants.js";
25
25
  import { _toNativeType, _toNativeTypes } from "./core/types.js";
26
26
  import { createLazyLoader } from "./core/lazy-loader.js";
@@ -42,9 +42,8 @@ import { createMemoryOps } from "./memory/operations.js";
42
42
  import { enableMirrors, wrapNative } from "./memory/mirror.js";
43
43
  import { addressOf as _addressOf, byref as _byref, cast as _cast, ptrToBuffer as _ptrToBuffer, POINTER as _POINTER, pointer as _pointer } from "./memory/pointer.js";
44
44
  import { FormatError as _FormatError, WinError as _WinError, ArgumentError } from "./platform/errors.js";
45
- import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField } from "./structures/helpers/common.js";
45
+ import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField, registerSimpleType } from "./structures/helpers/common.js";
46
46
  import { array as _array } from "./structures/helpers/array.js";
47
- import { _readBitField as _readBitFieldHelper, _writeBitField as _writeBitFieldHelper, _readUintFromBuffer, _writeUintToBuffer } from "./structures/helpers/bitfield.js";
48
47
  import { union as _union } from "./structures/helpers/union.js";
49
48
  import { struct as _struct } from "./structures/helpers/struct.js";
50
49
  import { createStructureClass } from "./structures/Structure.js";
@@ -256,8 +255,8 @@ function addressOf(ptr) {
256
255
  return _addressOf(ptr, alloc, native);
257
256
  }
258
257
 
259
- function byref(obj) {
260
- return _byref(obj);
258
+ function byref(obj, offset = 0) {
259
+ return _byref(obj, offset, native);
261
260
  }
262
261
 
263
262
  function cast(ptr, targetType) {
@@ -270,8 +269,18 @@ function ptrToBuffer(address, size) {
270
269
  return _ptrToBuffer(address, size, native);
271
270
  }
272
271
 
272
+ // Python: POINTER(T) is POINTER(T) e (T * n) is (T * n): un tipo per base.
273
+ const pointerTypes = new WeakMap();
274
+ const arrayTypes = new WeakMap();
275
+
273
276
  function POINTER(baseType) {
274
- return _POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p, native);
277
+ const cacheable = baseType !== null && (typeof baseType === "object" || typeof baseType === "function");
278
+ let type = cacheable ? pointerTypes.get(baseType) : undefined;
279
+ if (type === undefined) {
280
+ type = _POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p, native);
281
+ if (cacheable) pointerTypes.set(baseType, type);
282
+ }
283
+ return type;
275
284
  }
276
285
 
277
286
  /**
@@ -291,7 +300,7 @@ function POINTER(baseType) {
291
300
  * ```
292
301
  */
293
302
  function pointer(obj) {
294
- return _pointer(obj, _POINTER, sizeof, alloc, readValue, writeValue, c_void_p, native);
303
+ return _pointer(obj, POINTER, sizeof, alloc, readValue, writeValue, c_void_p, native);
295
304
  }
296
305
 
297
306
  /**
@@ -320,8 +329,8 @@ function defineStruct(fields, options) {
320
329
  /**
321
330
  * Helper to define a JS class backed by a union definition.
322
331
  */
323
- function defineUnion(fields) {
324
- const def = union(fields);
332
+ function defineUnion(fields, options) {
333
+ const def = union(fields, options);
325
334
  class AutoUnion extends Union {}
326
335
  AutoUnion._structDef = def;
327
336
  AutoUnion._fields_ = fields;
@@ -350,19 +359,29 @@ memoryDeps.Union = Union;
350
359
  * Helper per creare array a dimensione fissa (come c_int * 5 in Python)
351
360
  * Ritorna un ArrayType wrapper con supporto per indexing arr[i]
352
361
  *
353
- * @param {string} elementType - Tipo degli elementi ('int32', 'float', etc.)
362
+ * @param {Function|Object} elementType - Tipo degli elementi (c_int32, Structure, etc.)
354
363
  * @param {number} count - Numero di elementi
355
364
  * @returns {Object} ArrayType con metodi getSize(), getLength(), create(), wrap()
356
365
  *
357
366
  * @example
358
- * const IntArray5 = array('int32', 5);
367
+ * const IntArray5 = array(c_int32, 5);
359
368
  * const arr = IntArray5.create([1, 2, 3, 4, 5]);
360
369
  * console.log(arr[0]); // 1 - indexing Python-like!
361
370
  * arr[2] = 42;
362
371
  * console.log(arr[2]); // 42
363
372
  */
364
373
  function array(elementType, count) {
365
- return _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p, ptrToBuffer);
374
+ const cacheable = elementType !== null && (typeof elementType === "object" || typeof elementType === "function");
375
+ let byCount = cacheable ? arrayTypes.get(elementType) : undefined;
376
+ let type = byCount?.get(count)?.deref();
377
+ if (type === undefined) {
378
+ type = _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p, ptrToBuffer);
379
+ if (cacheable) {
380
+ if (byCount === undefined) arrayTypes.set(elementType, (byCount = new Map()));
381
+ cacheWeakValue(byCount, count, type);
382
+ }
383
+ }
384
+ return type;
366
385
  }
367
386
 
368
387
  // ============================================================================
@@ -413,9 +432,9 @@ function FormatError(code) {
413
432
  return _FormatError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
414
433
  }
415
434
 
416
- function WinError(code) {
417
- if (code === undefined) code = native.getCapturedLastError();
418
- return _WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p);
435
+ function WinError(code, descr) {
436
+ if (code === undefined || code === null) code = native.getCapturedLastError();
437
+ return _WinError(code, WinDLL, alloc, c_uint32, c_void, c_void_p, descr ?? undefined);
419
438
  }
420
439
 
421
440
  /**
@@ -424,26 +443,16 @@ function WinError(code) {
424
443
  * @param {number} bits - Numero di bit
425
444
  * @returns {Object} Definizione del bit field
426
445
  */
446
+ // Python: bitfield solo su interi e c_bool.
447
+ const bitFieldTypes = new Set([CType.INT8, CType.UINT8, CType.INT16, CType.UINT16, CType.INT32, CType.UINT32, CType.INT64, CType.UINT64, CType.LONG, CType.ULONG, CType.SIZE_T, CType.SSIZE_T, CType.BOOL]);
448
+
427
449
  function bitfield(baseType, bits) {
450
+ if (typeof baseType === "function" && baseType._isSimpleCData === true && !bitFieldTypes.has(baseType._type)) {
451
+ throw new TypeError(`bit fields not allowed for type ${baseType.name}`);
452
+ }
428
453
  return _bitfield(baseType, bits, sizeof);
429
454
  }
430
455
 
431
- /**
432
- * Helper per leggere un valore bit field da un buffer
433
- * @private
434
- */
435
- function _readBitField(buf, offset, baseType, bitOffset, bitSize) {
436
- return _readBitFieldHelper(buf, offset, baseType, bitOffset, bitSize, sizeof);
437
- }
438
-
439
- /**
440
- * Helper per scrivere un valore bit field in un buffer
441
- * @private
442
- */
443
- function _writeBitField(buf, offset, baseType, bitOffset, bitSize, newValue) {
444
- return _writeBitFieldHelper(buf, offset, baseType, bitOffset, bitSize, newValue, sizeof);
445
- }
446
-
447
456
  /**
448
457
  * Helper per definire struct con supporto per:
449
458
  * - Alignment corretto
@@ -533,6 +542,8 @@ const wintypes = createWinTypes(primitiveTypes, { Structure, POINTER, array });
533
542
  class HRESULT extends c_int32 {
534
543
  static _isHResult = true;
535
544
  }
545
+ registerSimpleType(HRESULT);
546
+ OleDLL.defaultRestype = HRESULT;
536
547
 
537
548
  // ============================================================================
538
549
  // Alias Python-compatibili per Memory Management
@@ -698,7 +709,8 @@ export { POINTER_SIZE, WCHAR_SIZE, NULL } from "./platform/constants.js";
698
709
  export const EXTERNAL_BUFFERS = externalBuffers;
699
710
 
700
711
  // Python ctypes.util.find_library equivalent
701
- export { find_library } from "./platform/find_library.js";
712
+ import { find_library as findLibrary } from "./platform/find_library.js";
713
+ export const find_library = (name) => findLibrary(name, native);
702
714
 
703
715
  // Lazy loader namespaces (Python's `ctypes.cdll.libname` / `ctypes.windll.libname`).
704
716
  export const cdll = createLazyLoader(CDLL);
@@ -28,6 +28,25 @@
28
28
  */
29
29
 
30
30
  import { mirrorAddress } from "./mirror.js";
31
+ import { resolveParameter } from "../structures/helpers/common.js";
32
+
33
+ // Fixed backing stores do not move; resizable/growable stores are never cached.
34
+ const memoryAddresses = new WeakMap();
35
+
36
+ function destinationAddress(memory, native) {
37
+ if (memory === null) return 0n;
38
+ if (typeof memory === "bigint") return memory;
39
+ const buffer = memory.buffer;
40
+ const cached = memoryAddresses.get(buffer);
41
+ if (cached !== undefined && cached.length === buffer.byteLength) {
42
+ return memory.byteOffset === 0 ? cached.address : cached.address + BigInt(memory.byteOffset);
43
+ }
44
+ const address = native.addressOf(memory);
45
+ if (buffer.byteLength !== 0 && !buffer.resizable && !buffer.growable) {
46
+ memoryAddresses.set(buffer, { address: address - BigInt(memory.byteOffset), length: buffer.byteLength });
47
+ }
48
+ return address;
49
+ }
31
50
 
32
51
  /**
33
52
  * Allocates a zero-initialized buffer of the specified size.
@@ -101,7 +120,7 @@ export function decodeWide(buf, wcharSize) {
101
120
  for (let off = 0; off + 3 < buf.length; off += 4) {
102
121
  const cp = buf.readUInt32LE(off);
103
122
  if (cp === 0) break;
104
- out += String.fromCodePoint(cp);
123
+ out += String.fromCodePoint(cp > 0x10ffff ? 0xfffd : cp);
105
124
  }
106
125
  return out;
107
126
  }
@@ -392,7 +411,7 @@ export function create_unicode_buffer(init, size, native) {
392
411
  * ```
393
412
  */
394
413
  export function string_at(address, size, native) {
395
- return native.readCString(address, size);
414
+ return native.readCString(stringSource(address, native), size);
396
415
  }
397
416
 
398
417
  /**
@@ -420,10 +439,20 @@ export function string_at(address, size, native) {
420
439
  * ```
421
440
  */
422
441
  export function wstring_at(address, size, native) {
423
- if (address === null || address === undefined) {
424
- return null;
425
- }
426
- return native.readWString(address, size);
442
+ return native.readWString(stringSource(address, native), size);
443
+ }
444
+
445
+ /**
446
+ * Source of string_at / wstring_at, as Python's c_void_p.from_param: the
447
+ * memory of instances and arrays, the value of pointers, c_void_p, c_char_p
448
+ * and c_wchar_p, `_as_parameter_`. Buffer or address; NULL gives null.
449
+ */
450
+ function stringSource(value, native) {
451
+ if (value === null || value === undefined || typeof value === "bigint" || typeof value === "number") return value;
452
+ // Array proxies pass Buffer.isBuffer but are resolved through _buffer.
453
+ if (Buffer.isBuffer(value) && value._buffer === undefined) return mirrorAddress(value) ?? value;
454
+ const memory = memoryOf(value, native, "address", true);
455
+ return memory instanceof Uint8Array && !Buffer.isBuffer(memory) ? Buffer.from(memory.buffer, memory.byteOffset, memory.byteLength) : memory;
427
456
  }
428
457
 
429
458
  /**
@@ -449,33 +478,60 @@ export function wstring_at(address, size, native) {
449
478
  * ```
450
479
  */
451
480
  export function memmove(dst, src, count, native) {
452
- const to = memoryOf(dst, native, "dst");
453
- const from = memoryOf(src, native, "src");
481
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("memmove: count must be a non-negative safe integer");
482
+ const to = memoryOf(dst, native, "dst", count === 0);
483
+ const from = memoryOf(src, native, "src", count === 0);
484
+ if (count === 0) return destinationAddress(to, native);
454
485
  // Come Buffer.copy, la copia si ferma alla fine dei Buffer coinvolti.
455
486
  let n = count;
456
487
  if (typeof to !== "bigint") n = Math.min(n, to.length);
457
488
  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);
489
+ if (n <= 0) return destinationAddress(to, native);
490
+ // TypedArray.set gestisce anche la sovrapposizione (stesso ArrayBuffer).
491
+ if (typeof to !== "bigint" && typeof from !== "bigint") {
492
+ to.set(n === from.length ? from : from.subarray(0, n));
493
+ return destinationAddress(to, native);
494
+ }
495
+ return native.memmove(to, from, n);
461
496
  }
462
497
 
463
- // Memoria di un argomento di memmove/memset, come Python: Buffer, istanze
464
- // ctypes (struct, array, c_*), puntatori o un indirizzo (BigInt/number).
498
+ // Memoria di un argomento di memmove/memset, come Python: Buffer, ogni
499
+ // TypedArray/DataView/ArrayBuffer (come vista a byte), istanze ctypes (struct,
500
+ // array, c_*), puntatori o un indirizzo (BigInt/number).
465
501
  // Gli indirizzi (anche quello originale di una copia, memory/mirror.js) sono
466
502
  // letti e scritti dal nativo, senza creare un Buffer esterno.
467
- function memoryOf(value, native, name) {
503
+ function memoryOf(value, native, name, allowNull = false) {
504
+ value = resolveParameter(value);
505
+ if (ArrayBuffer.isView(value) && value._buffer === undefined) {
506
+ return mirrorAddress(value) ?? (value instanceof Uint8Array ? value : new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
507
+ }
468
508
  if (value !== null && typeof value === "object") {
509
+ // c_void_p / c_char_p / c_wchar_p: the memory they point to, as in Python.
510
+ const T = value.constructor;
511
+ if (T?._isSimpleCData === true && (T._type === native.CType.POINTER || T._type === native.CType.STRING || T._type === native.CType.WSTRING)) {
512
+ const slot = value._buffer;
513
+ return addressOrNull(native.POINTER_SIZE === 8 ? slot.readBigUInt64LE(0) : BigInt(slot.readUInt32LE(0)), name, allowNull);
514
+ }
469
515
  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;
516
+ if (value._pointerType !== undefined) return addressOrNull(value.address, name, allowNull);
517
+ if (ArrayBuffer.isView(value)) {
518
+ return mirrorAddress(value) ?? (value instanceof Uint8Array ? value : new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
519
+ }
520
+ if (value instanceof ArrayBuffer || (typeof SharedArrayBuffer === "function" && value instanceof SharedArrayBuffer)) {
521
+ return new Uint8Array(value);
522
+ }
523
+ if (value._as_parameter_ !== undefined) return memoryOf(value._as_parameter_, native, name, allowNull);
472
524
  }
473
- if (typeof value === "bigint" || typeof value === "number") return addressOrNull(value, name);
525
+ if (typeof value === "bigint" || typeof value === "number") return addressOrNull(value, name, allowNull);
526
+ if (value === null) return addressOrNull(0n, name, allowNull);
474
527
  throw new TypeError(`${name} must be a Buffer, a ctypes instance, a pointer or an address`);
475
528
  }
476
529
 
477
- function addressOrNull(value, name) {
478
- if (!value) throw new TypeError(`${name} is a NULL pointer`);
530
+ function addressOrNull(value, name, allowNull = false) {
531
+ if (!value) {
532
+ if (allowNull) return null;
533
+ throw new TypeError(`${name} is a NULL pointer`);
534
+ }
479
535
  return BigInt(value);
480
536
  }
481
537
 
@@ -500,10 +556,14 @@ function addressOrNull(value, name) {
500
556
  * ```
501
557
  */
502
558
  export function memset(dst, value, count, native) {
503
- const to = memoryOf(dst, native, "dst");
559
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("memset: count must be a non-negative safe integer");
560
+ const to = memoryOf(dst, native, "dst", count === 0);
561
+ if (count === 0) return destinationAddress(to, native);
504
562
  if (typeof to !== "bigint") {
505
- to.fill(value, 0, count);
563
+ // Come memmove, si ferma alla fine della memoria JS.
564
+ to.fill(value, 0, Math.max(0, Math.min(count, to.length)));
565
+ return destinationAddress(to, native);
506
566
  } else if (count > 0) {
507
- native.memmove(to, Buffer.alloc(count, value), count);
567
+ return native.memmove(to, Buffer.alloc(count, value), count);
508
568
  }
509
569
  }
@@ -28,6 +28,7 @@
28
28
  */
29
29
 
30
30
  import { flush, mirrorsActive, refresh } from "./mirror.js";
31
+ import { copyInstance, isScalarSubclass, scalarView } 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,33 @@ 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
+ if (isScalarSubclass(type)) return scalarView(type, ptr.subarray(offset, offset + size));
155
+ return type._reader(ptr, offset);
135
156
  }
136
157
 
137
- // Structure class
158
+ let def;
138
159
  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}`);
160
+ def = type._structDef || type._buildStruct();
161
+ } else if (typeof type === "function" && type.prototype instanceof getUnion()) {
162
+ def = type._unionDef || type._buildUnion();
163
+ } else if (typeof type === "object" && type !== null && type._isStructType && typeof type.toObject === "function") {
164
+ def = type;
165
+ } else {
166
+ throw new TypeError(`readValue: unsupported type ${type}`);
167
+ }
168
+ ptr = memoryAt(ptr, offset, () => def.size, "readValue");
169
+ checkBounds(ptr, offset, def.size, "Read");
170
+ return def.toObject(ptr.subarray(offset, offset + def.size));
153
171
  }
154
172
 
155
173
  /**
@@ -159,22 +177,12 @@ export function createMemoryOps(deps) {
159
177
  if (typeof offset !== "number" || offset < 0) {
160
178
  throw new RangeError("offset must be a non-negative number");
161
179
  }
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
- }
180
+ ptr = memoryAt(ptr, offset, () => sizeof(type), "writeValue");
168
181
 
169
182
  // SimpleCData class: usa _writer diretto
170
183
  if (typeof type === "function" && type._isSimpleCData) {
171
- if (!Buffer.isBuffer(ptr)) {
172
- throw new TypeError("writeValue requires a Buffer");
173
- }
174
184
  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
- }
185
+ checkBounds(ptr, offset, size, "Write");
178
186
  type._writer(ptr, offset, value);
179
187
  if (mirrorsActive) flush(ptr, offset, size);
180
188
  return type._size;
@@ -183,9 +191,11 @@ export function createMemoryOps(deps) {
183
191
  // Structure/Union class o def — tutti gestiti con la stessa logica:
184
192
  // o value è un Buffer (copia raw) o è un object (set field-by-field).
185
193
  const writeComposite = (def) => {
194
+ checkBounds(ptr, offset, def.size, "Write");
186
195
  const tempBuf = ptr.subarray(offset, offset + def.size);
187
- if (Buffer.isBuffer(value)) {
188
- value.copy(tempBuf, 0, 0, def.size);
196
+ if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
197
+ // Istanza struct/union: copia dei byte (Python), non campo per campo.
198
+ copyInstance(tempBuf, 0, def.size, value, 0, def);
189
199
  if (mirrorsActive) flush(tempBuf);
190
200
  } else if (typeof value === "object" && value !== null) {
191
201
  for (const [k, v] of Object.entries(value)) {