node-ctypes 2.4.0 → 2.5.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.
@@ -251,15 +251,11 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
251
251
  return targetType.fromBuffer(ptr);
252
252
  }
253
253
 
254
- let addr;
255
- if (typeof ptr === "bigint") {
256
- addr = ptr;
257
- } else if (typeof ptr === "number") {
258
- addr = BigInt(ptr);
259
- } else {
260
- throw new TypeError("cast(): ptr must be a BigInt, number, Buffer, ctypes instance, or PointerInstance");
261
- }
262
- return targetType.fromAddress(addr);
254
+ return targetType.fromAddress(castSourceAddress(ptr, native), ptr);
255
+ }
256
+
257
+ if (typeof targetType === "function" && targetType._isFuncPtr === true) {
258
+ return keepFunctionOwner(targetType(castSourceAddress(ptr, native)), ptr);
263
259
  }
264
260
 
265
261
  // c_void_p / c_char_p / c_wchar_p: an instance pointing to the source,
@@ -267,7 +263,7 @@ export function cast(ptr, targetType, readValue, sizeof, ptrToBuffer, native) {
267
263
  if (typeof targetType === "function" && targetType._isSimpleCData === true && isPointerValued(targetType, native)) {
268
264
  const result = new targetType();
269
265
  writePointerField(result._buffer, 0, ptr == null || ptr === 0 || ptr === 0n ? 0n : castSourceAddress(ptr, native), native.POINTER_SIZE);
270
- if (typeof ptr === "object") keepAlive(result._buffer, 0, ptr);
266
+ if (typeof ptr === "object" || typeof ptr === "function") keepAlive(result._buffer, 0, ptr);
271
267
  return result;
272
268
  }
273
269
 
@@ -308,7 +304,7 @@ function isPointerValued(type, native) {
308
304
  function castSourceAddress(ptr, native) {
309
305
  if (typeof ptr === "bigint") return ptr;
310
306
  if (typeof ptr === "number") return BigInt(ptr);
311
- if (ptr !== null && typeof ptr === "object") {
307
+ if (ptr !== null && (typeof ptr === "object" || typeof ptr === "function")) {
312
308
  if (ptr._pointerType !== undefined) return ptr.address;
313
309
  const T = ptr.constructor;
314
310
  if (T?._isSimpleCData === true && isPointerValued(T, native)) {
@@ -316,7 +312,8 @@ function castSourceAddress(ptr, native) {
316
312
  }
317
313
  if (Buffer.isBuffer(ptr._buffer)) return addressOf(ptr._buffer, null, native);
318
314
  if (Buffer.isBuffer(ptr)) return addressOf(ptr, null, native);
319
- if (ptr._as_parameter_ !== undefined) return castSourceAddress(ptr._as_parameter_, native);
315
+ const parameter = ptr._as_parameter_;
316
+ if (parameter !== undefined) return castSourceAddress(parameter, native);
320
317
  }
321
318
  throw new TypeError("cast(): ptr must be a BigInt, number, Buffer, ctypes instance, or PointerInstance");
322
319
  }
@@ -419,28 +416,23 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
419
416
  !baseType._isArrayType &&
420
417
  !baseType._isFuncPtr;
421
418
 
422
- // Se non è thunk, `baseType` rimane il valore passato e `baseSize` è
423
- // calcolabile subito. Se è thunk, entrambi vengono rimpiazzati al primo
424
- // uso, senza mutare le chiusure dei trap.
419
+ const isAggregate = (type) => typeof type === "function" && (typeof type._buildStruct === "function" || typeof type._buildUnion === "function");
420
+ // A pointer does not materialize or finalize its incomplete pointee.
425
421
  let baseSize;
426
422
  let scalarSubclass = isScalarSubclass(baseType);
427
423
  let _lazyResolved = false;
428
- function resolveIfLazy() {
424
+ function resolveType() {
429
425
  if (!isLazyThunk || _lazyResolved) return;
430
- const resolved = baseType();
431
- // NB: impostare `_lazyResolved = true` e `baseType = resolved` PRIMA di
432
- // chiamare sizeof(). sizeof può innescare `resolved._buildStruct()` che
433
- // a sua volta riattraversa i fields, tra cui questo stesso POINTER —
434
- // senza il flag risolto, si entrerebbe in ricorsione infinita.
435
- // La size del POINTER (pointer word) è comunque costante (POINTER_SIZE);
436
- // `baseSize` serve solo per pointer arithmetic che avviene dopo la
437
- // costruzione della struct, quando `resolved` è completamente definito.
438
- baseType = resolved;
426
+ baseType = baseType();
439
427
  scalarSubclass = isScalarSubclass(baseType);
440
428
  _lazyResolved = true;
441
- baseSize = typeof resolved === "object" ? resolved.size : sizeof(resolved);
429
+ if (!isAggregate(baseType)) baseSize = typeof baseType === "object" ? baseType.size : sizeof(baseType);
430
+ }
431
+ function resolveSize() {
432
+ resolveType();
433
+ baseSize ??= typeof baseType === "object" ? baseType.size : sizeof(baseType);
442
434
  }
443
- if (!isLazyThunk) {
435
+ if (!isLazyThunk && !isAggregate(baseType)) {
444
436
  baseSize = typeof baseType === "object" ? baseType.size : sizeof(baseType);
445
437
  }
446
438
 
@@ -542,9 +534,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
542
534
  * Supports .contents property and [index] access for pointer arithmetic.
543
535
  */
544
536
  function createPointerInstance(addressOrBuffer, keep, memory) {
545
- // Risolvi il thunk lazy alla prima creazione di istanza: a questo
546
- // punto la classe target è sicuramente inizializzata.
547
- resolveIfLazy();
537
+ resolveType();
548
538
 
549
539
  let _address = 0n;
550
540
  let _buffer = null;
@@ -642,7 +632,10 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
642
632
  const instance = {
643
633
  _pointerType: PointerType,
644
634
  _baseType: baseType,
645
- _baseSize: baseSize,
635
+ get _baseSize() {
636
+ resolveSize();
637
+ return baseSize;
638
+ },
646
639
 
647
640
  /**
648
641
  * Get the raw address as BigInt
@@ -681,6 +674,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
681
674
  if (_address === 0n && !_buffer) {
682
675
  throw new Error("NULL pointer access");
683
676
  }
677
+ resolveSize();
684
678
  if (isPointerBase()) {
685
679
  return readPointerAt(_buffer, _address, 0, getMemory());
686
680
  }
@@ -698,6 +692,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
698
692
  sync();
699
693
  // Python: assegnare un'istanza ri-punta il puntatore a quell'istanza.
700
694
  if (value !== null && typeof value === "object" && (value._isSimpleCDataInstance === true || value._structDef !== undefined || value._arrayType !== undefined) && Buffer.isBuffer(value._buffer)) {
695
+ resolveSize();
701
696
  // Python accetta anche un'istanza di un altro tipo; una più piccola
702
697
  // del tipo puntato farebbe leggere e scrivere oltre la sua memoria.
703
698
  if (value._buffer.length < baseSize) {
@@ -709,6 +704,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
709
704
  if (_address === 0n && !_buffer) {
710
705
  throw new Error("NULL pointer access");
711
706
  }
707
+ resolveSize();
712
708
  if (isPointerBase()) {
713
709
  writePointerAt(_buffer, _address, 0, value, getMemory());
714
710
  } else if (_buffer) {
@@ -778,6 +774,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
778
774
  */
779
775
  add(n) {
780
776
  sync();
777
+ resolveSize();
781
778
  const offsetBytes = BigInt(n) * BigInt(baseSize);
782
779
  // Il nuovo puntatore tiene viva la memoria di questo (Python _objects).
783
780
  return createPointerInstance(_address + offsetBytes, _buffer ?? _objects, getMemory());
@@ -806,6 +803,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
806
803
  if (target.isNull) {
807
804
  throw new Error("NULL pointer access");
808
805
  }
806
+ resolveSize();
809
807
  const offset = index * baseSize;
810
808
  if (isPointerBase()) {
811
809
  return readPointerAt(_buffer, _address, offset, getMemory());
@@ -831,6 +829,7 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
831
829
  if (target.isNull) {
832
830
  throw new Error("NULL pointer access");
833
831
  }
832
+ resolveSize();
834
833
  const offset = index * baseSize;
835
834
  if (isPointerBase()) {
836
835
  writePointerAt(_buffer, _address, offset, value, getMemory());
@@ -856,11 +855,15 @@ export function POINTER(baseType, sizeof, alloc, readValue, writeValue, c_void_p
856
855
  // accesso — così l'uso come `POINTER(() => Node)` in field type resta
857
856
  // Python-compatibile senza forzare l'utente a invalidare manualmente.
858
857
  get _pointerTo() {
859
- resolveIfLazy();
858
+ resolveType();
859
+ return baseType;
860
+ },
861
+ get _type_() {
862
+ resolveType();
860
863
  return baseType;
861
864
  },
862
865
  get _baseSize() {
863
- resolveIfLazy();
866
+ resolveSize();
864
867
  return baseSize;
865
868
  },
866
869
  size: native.POINTER_SIZE,
@@ -954,9 +957,12 @@ export function pointer(obj, POINTER_fn, sizeof, alloc, readValue, writeValue, c
954
957
  let targetBuffer;
955
958
  let baseType;
956
959
 
957
- // Le istanze di array sono Proxy su un Buffer (Buffer.isBuffer è vero): la
958
- // loro memoria è `_buffer`, controllato per primo.
959
- if (obj !== null && typeof obj === "object" && Buffer.isBuffer(obj._buffer)) {
960
+ if (obj !== null && typeof obj === "object" && obj._pointerType !== undefined) {
961
+ targetBuffer = obj._pointerSlot;
962
+ baseType = obj._pointerType;
963
+ }
964
+ // Array proxies expose their actual memory through _buffer.
965
+ else if (obj !== null && typeof obj === "object" && Buffer.isBuffer(obj._buffer)) {
960
966
  // Structure/Union instance, array or SimpleCData with _buffer
961
967
  targetBuffer = obj._buffer;
962
968
  // Get the base type for POINTER creation
@@ -91,13 +91,42 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
91
91
 
92
92
  // Definizione con cui è stata creata l'istanza (layout dei suoi byte).
93
93
  const kDef = Symbol("def");
94
+ // A field may shadow the public constructor property.
95
+ const kCtor = Symbol("constructor");
94
96
  // Istanze dei campi struct/union annidati, create al primo accesso: sono
95
97
  // viste sulla memoria dell'istanza, quindi restano valide.
96
98
  const kViews = Symbol("views");
97
99
  // Nomi dei campi con un accessor installato da noi, per prototipo.
98
100
  const installedNames = new WeakMap();
99
101
  // Nomi che restano proprietà della libreria anche se usati come campi.
100
- const reservedNames = new Set(["constructor", "_buffer", "__buffer", "_structDef", "__structDef"]);
102
+ const reservedNames = new Set(["_buffer", "__buffer", "_structDef", "__structDef"]);
103
+ const finalizedClasses = new WeakSet();
104
+
105
+ function assignClassFields(Ctor, fields) {
106
+ if (finalizedClasses.has(Ctor)) throw new TypeError("_fields_ is final");
107
+ Object.defineProperty(Ctor, "_fields_", { value: fields, writable: true, enumerable: true, configurable: true });
108
+ Ctor._structDef = null;
109
+ }
110
+
111
+ function finalizeFields(Ctor) {
112
+ if (finalizedClasses.has(Ctor)) return;
113
+ if (Object.hasOwn(Ctor, "_fields_")) {
114
+ const fields = Ctor._fields_;
115
+ Object.defineProperty(Ctor, "_fields_", {
116
+ get() {
117
+ return fields;
118
+ },
119
+ set(value) {
120
+ assignClassFields(this, value);
121
+ },
122
+ enumerable: true,
123
+ configurable: false,
124
+ });
125
+ }
126
+ finalizedClasses.add(Ctor);
127
+ const own = Ctor[kStructDef];
128
+ if (own?.owner === Ctor) own.finalized = true;
129
+ }
101
130
 
102
131
  // Percorso generale di un campo: istanza con un'altra definizione (creata
103
132
  // prima di un'invalidazione del layout), copia di memoria nativa (Electron,
@@ -124,6 +153,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
124
153
  // veloce usa il lettore/scrittore precompilato della definizione della classe.
125
154
  function installFieldAccessors(Ctor, def) {
126
155
  const proto = Ctor.prototype;
156
+ Object.defineProperty(proto, kCtor, { value: Ctor, configurable: true });
127
157
  for (const name of installedNames.get(proto) ?? []) {
128
158
  delete proto[name];
129
159
  }
@@ -281,11 +311,12 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
281
311
  */
282
312
  class Structure {
283
313
  constructor(...args) {
284
- const Ctor = this.constructor;
314
+ const Ctor = new.target;
285
315
  // Definizione propria della classe (percorso caldo di `new`: una lettura
286
316
  // di proprietà invece di Object.hasOwn).
287
317
  const own = Ctor[kStructDef];
288
318
  const def = own !== undefined && own.owner === Ctor ? own.def : Ctor._buildStruct();
319
+ if (own?.owner !== Ctor || !own.finalized) finalizeFields(Ctor);
289
320
  let buf;
290
321
 
291
322
  // Support positional args: new Point(10,20)
@@ -351,7 +382,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
351
382
  }
352
383
 
353
384
  get [Symbol.toStringTag]() {
354
- return this.constructor.name || "Structure";
385
+ return this[kCtor]?.name || "Structure";
355
386
  }
356
387
 
357
388
  // I campi non sono proprietà proprie (come in Python): JSON.stringify e
@@ -361,7 +392,21 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
361
392
  }
362
393
 
363
394
  [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
364
- return `${this.constructor.name || "Structure"} ${inspect(this.toObject(), options)}`;
395
+ return `${this[kCtor]?.name || "Structure"} ${inspect(this.toObject(), options)}`;
396
+ }
397
+
398
+ static get _fields_() {
399
+ return undefined;
400
+ }
401
+
402
+ static set _fields_(fields) {
403
+ assignClassFields(this, fields);
404
+ }
405
+
406
+ static _finalizeFields() {
407
+ const def = this._structDef || this._buildStruct();
408
+ finalizeFields(this);
409
+ return def;
365
410
  }
366
411
 
367
412
  // Static getters for size, alignment, and fields (enables use as nested type)
@@ -464,8 +509,9 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
464
509
  return;
465
510
  }
466
511
  // { owner, def }: una sottoclasse eredita la proprietà ma non è `owner`.
467
- Object.defineProperty(this, kStructDef, { value: { owner: this, def }, configurable: true, writable: true });
512
+ Object.defineProperty(this, kStructDef, { value: { owner: this, def, finalized: finalizedClasses.has(this) }, configurable: true, writable: true });
468
513
  installFieldAccessors(this, def);
514
+ if (Object.hasOwn(this, "_fields_")) finalizeFields(this);
469
515
  }
470
516
 
471
517
  // Classe base con un layout (Python: la sottoclasse ne estende i campi),
@@ -505,7 +551,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
505
551
  if (!anonymous.has(name)) return [name, type];
506
552
  // Classe Structure/Union: la sua definizione, e la classe per le istanze.
507
553
  if (typeof type === "function" && typeof type._buildStruct === "function") {
508
- return [name, { anonymous: true, type: type._structDef || type._buildStruct(), cls: type }];
554
+ return [name, { anonymous: true, type: type._finalizeFields(), cls: type }];
509
555
  }
510
556
  return [name, { anonymous: true, type }];
511
557
  });
@@ -2,23 +2,28 @@ import { flush, kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive, refre
2
2
  import { POINTER_SIZE } from "../../platform/constants.js";
3
3
 
4
4
  const simpleTypes = new WeakSet();
5
+ export const activeArgumentOwners = new Set();
5
6
  export const byrefOwners = new WeakMap();
7
+ export const structArgumentFactories = new WeakMap();
6
8
 
7
9
  export function resolveParameter(value, owners) {
8
- let seen;
9
- for (let depth = 0; value !== null && (typeof value === "object" || typeof value === "function"); depth++) {
10
- if (owners !== undefined) owners.push(value);
11
- if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
12
- if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
13
- const parameter = value._as_parameter_;
14
- if (parameter === undefined) return value;
15
- if (depth >= 128) throw new RangeError("_as_parameter_ maximum depth exceeded");
16
- seen ??= new Set();
17
- if (seen.has(value)) throw new TypeError("_as_parameter_ cycle detected");
18
- seen.add(value);
19
- value = parameter;
10
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
11
+ if (owners !== undefined) owners.push(value);
12
+ if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
13
+ if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
14
+ const parameter = value._as_parameter_;
15
+ if (parameter === undefined) return value;
16
+ if (parameter === null || (typeof parameter !== "object" && typeof parameter !== "function")) return parameter;
17
+ if (owners !== undefined) return resolveParameter(parameter, owners);
18
+
19
+ // Resolver-only memory operations also retain parents while nested getters can collect.
20
+ const retained = [value];
21
+ activeArgumentOwners.add(retained);
22
+ try {
23
+ return resolveParameter(parameter, retained);
24
+ } finally {
25
+ activeArgumentOwners.delete(retained);
20
26
  }
21
- return value;
22
27
  }
23
28
 
24
29
  export function sourceBytes(source, offset, size, name) {
@@ -37,7 +37,7 @@ import { bitFieldAccessors } from "./bitfield.js";
37
37
  import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
39
  import { isMirror, syncDefinition } from "../../memory/mirror.js";
40
- import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
40
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, writePointerField } from "./common.js";
41
41
 
42
42
  /**
43
43
  * Creates a struct type definition with proper alignment and padding.
@@ -118,7 +118,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
118
118
  const ownDefs = [];
119
119
  for (const [name, type] of fieldEntries(fields)) {
120
120
  // Validate field name
121
- if (!name || typeof name !== "string" || name.trim().length === 0) {
121
+ if (typeof name !== "string" || (!Array.isArray(fields) && !(fields instanceof Map) && name.trim().length === 0)) {
122
122
  throw new TypeError("Field name must be a non-empty string");
123
123
  }
124
124
  if (fieldNames.has(name)) {
@@ -134,7 +134,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
134
134
  let def = type;
135
135
  if (typeof type === "function" && typeof type._buildStruct === "function") {
136
136
  cls = type;
137
- def = type._structDef || type._buildStruct();
137
+ def = type._finalizeFields();
138
138
  }
139
139
  if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
140
140
  throw new TypeError(`anonymous field "${name}" must be a structure or union`);
@@ -154,7 +154,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
154
154
  }
155
155
  // Structure / Union class (Union estende Structure)
156
156
  if (typeof type === "function" && type.prototype instanceof Structure) {
157
- const nested = type._structDef || type._buildStruct();
157
+ const nested = type._finalizeFields();
158
158
  // `cls`: Python restituisce un'istanza della classe annidata, sulla
159
159
  // stessa memoria.
160
160
  return { name, type: nested, cls: type, size: nested.size, alignment: nested.alignment, isNested: true };
@@ -294,6 +294,28 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
294
294
  }
295
295
  }
296
296
 
297
+ function createBuffer(values) {
298
+ const buf = alloc(totalSize);
299
+ buf.fill(0);
300
+
301
+ for (const field of fieldDefs) {
302
+ if (Object.hasOwn(values, field.name) && values[field.name] !== undefined) {
303
+ structDef.set(buf, field.name, values[field.name]);
304
+ }
305
+ }
306
+
307
+ for (const field of fieldDefs) {
308
+ if (field.isAnonymous && field.type && field.type.fields) {
309
+ for (const subField of field.type.fields) {
310
+ if (Object.hasOwn(values, subField.name) && values[subField.name] !== undefined) {
311
+ structDef.set(buf, subField.name, values[subField.name]);
312
+ }
313
+ }
314
+ }
315
+ }
316
+ return buf;
317
+ }
318
+
297
319
  const structDef = {
298
320
  size: totalSize,
299
321
  alignment: maxAlignment,
@@ -313,29 +335,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
313
335
  * @returns {Proxy} Proxy-based struct instance
314
336
  */
315
337
  create(values = {}) {
316
- const buf = alloc(totalSize);
317
- buf.fill(0); // Inizializza a zero
318
-
319
- // Prima imposta i campi diretti
320
- for (const field of fieldDefs) {
321
- if (values[field.name] !== undefined) {
322
- structDef.set(buf, field.name, values[field.name]);
323
- }
324
- }
325
-
326
- // Poi gestisci i campi anonymous - i loro campi possono essere passati direttamente nell'oggetto values
327
- for (const field of fieldDefs) {
328
- if (field.isAnonymous && field.type && field.type.fields) {
329
- for (const subField of field.type.fields) {
330
- if (values[subField.name] !== undefined) {
331
- structDef.set(buf, subField.name, values[subField.name]);
332
- }
333
- }
334
- }
335
- }
336
-
337
338
  return new Proxy(
338
- buf,
339
+ createBuffer(values),
339
340
  buildWrapper(structDef, {
340
341
  instanceTag: "StructInstance",
341
342
  exposeAnonymous: true,
@@ -631,6 +632,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
631
632
 
632
633
  // Leggi tutti i campi in una volta (eager approach)
633
634
  for (const field of fieldDefs) {
635
+ if (field.name === "__proto__" && !field.isAnonymous) {
636
+ Object.defineProperty(result, field.name, { value: undefined, writable: true, enumerable: true, configurable: true });
637
+ }
634
638
  if (field.isBitField) {
635
639
  result[field.name] = field.readBits(buf);
636
640
  } else if (field.isNested) {
@@ -638,6 +642,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
638
642
  const nestedObj = field.type.toObject(nestedBuf);
639
643
  if (field.isAnonymous) {
640
644
  // Anonymous fields: promote their fields to parent level
645
+ if (Object.hasOwn(nestedObj, "__proto__")) {
646
+ Object.defineProperty(result, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true });
647
+ }
641
648
  Object.assign(result, nestedObj);
642
649
  } else {
643
650
  result[field.name] = nestedObj;
@@ -686,5 +693,14 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
686
693
  return this.toObject(this.create(values)._buffer);
687
694
  };
688
695
 
696
+ if (fieldDefs.every((field) => !field.isBitField && !field.isNested && !field.isArray && !field.isPointer && !field.type._isPointerValued && !isScalarSubclass(field.type))) {
697
+ const create = structDef.create;
698
+ structArgumentFactories.set(structDef, (values) => {
699
+ // A later create override must still run, with the definition as receiver.
700
+ const current = structDef.create;
701
+ return current === create ? createBuffer(values) : current.call(structDef, values);
702
+ });
703
+ }
704
+
689
705
  return syncDefinition(structDef);
690
706
  }
@@ -135,7 +135,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
135
135
  fieldDef.cls = type.cls;
136
136
  if (typeof def === "function" && typeof def._buildStruct === "function") {
137
137
  fieldDef.cls = def;
138
- def = def._structDef || def._buildStruct();
138
+ def = def._finalizeFields();
139
139
  }
140
140
  if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
141
141
  throw new TypeError(`anonymous field "${name}" must be a structure or union`);
@@ -147,11 +147,11 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
147
147
  alignment = def.alignment;
148
148
  }
149
149
  // Nested struct (object form or class form)
150
- else if (_isStruct(type)) {
150
+ else if ((typeof type === "function" && type.prototype instanceof Structure) || _isStruct(type)) {
151
151
  // Normalize type: if it's a Structure/Union class, get its _structDef
152
152
  let nestedStruct = type;
153
153
  if (typeof type === "function" && typeof type._buildStruct === "function") {
154
- nestedStruct = type._structDef || type._buildStruct();
154
+ nestedStruct = type._finalizeFields();
155
155
  fieldDef.type = nestedStruct;
156
156
  // Python restituisce un'istanza della classe annidata.
157
157
  fieldDef.cls = type;
@@ -326,7 +326,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
326
326
 
327
327
  // Prima imposta i campi diretti
328
328
  for (const field of fieldDefs) {
329
- if (values[field.name] !== undefined) {
329
+ if (Object.hasOwn(values, field.name) && values[field.name] !== undefined) {
330
330
  unionDef.set(buf, field.name, values[field.name]);
331
331
  }
332
332
  }
@@ -118,8 +118,9 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
118
118
  if (typeof val === "number") return val;
119
119
  if (typeof val === "boolean") return +val;
120
120
  if (typeof val === "bigint") {
121
- if (val < -(2n ** 63n) || val >= 2n ** 64n) throw new RangeError("BigInt out of range for a floating point argument");
122
- return Number(val);
121
+ const number = Number(val);
122
+ if (!Number.isFinite(number)) throw new RangeError("int too large to convert to float");
123
+ return number;
123
124
  }
124
125
  throw new TypeError(`must be real number, not ${typeName(val)}`);
125
126
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",