node-ctypes 2.3.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.
@@ -34,10 +34,10 @@
34
34
  */
35
35
 
36
36
  import { bitFieldAccessors } from "./bitfield.js";
37
- import { computeLayout, isGccLayout } from "./layout.js";
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, simpleFieldWriter, writePointerField } from "./common.js";
40
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
41
41
 
42
42
  /**
43
43
  * Creates a struct type definition with proper alignment and padding.
@@ -88,7 +88,10 @@ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWrit
88
88
  * ```
89
89
  */
90
90
  // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
91
- const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fromAddress(address));
91
+ const pointerOrNull = (ptrType, address, buf, offset) => {
92
+ const owner = pointerOwner(buf, offset, address);
93
+ return address === 0n ? null : ptrType.fromAddress(address, owner);
94
+ };
92
95
 
93
96
  export function struct(fields, options = {}, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
94
97
  // Validate inputs
@@ -98,12 +101,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
98
101
  }
99
102
 
100
103
  // Python _pack_: `pack` (massimo allineamento), o `packed: true` (= pack 1).
101
- const packValue = typeof options.pack === "number" ? options.pack : options.packed ? 1 : 0;
104
+ const packValue = normalizePack(options.pack ?? (options.packed ? 1 : 0));
102
105
  // `swapped` selects _readerBE/_writerBE on primitive SimpleCData fields and
103
106
  // lays out bitfields from the big end. Used by BigEndianStructure /
104
107
  // LittleEndianStructure (on LE host, swapped=true means "use BE").
105
108
  const swapped = options.swapped === true;
106
- const gccLayout = isGccLayout(options.layout, packValue);
109
+ const gccLayout = isGccLayout(options.layout, packValue, options.pack != null || options.packed === true);
107
110
  // Python: una sottoclasse con _fields_ estende il layout della base, i cui
108
111
  // campi restano agli stessi offset.
109
112
  const base = options.base ?? null;
@@ -162,6 +165,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
162
165
  }
163
166
  // Array type: alignment == element alignment (C standard).
164
167
  if (_isArrayType(type)) {
168
+ if (swapped) type = type._swappedType ?? type;
165
169
  const elemSize = sizeof(type.elementType);
166
170
  const alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elemSize, native.POINTER_SIZE);
167
171
  return { name, type, size: type.getSize(), alignment, isArray: true };
@@ -246,11 +250,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
246
250
  bitSize: field.bitSize,
247
251
  signed: field.type?._signed === true,
248
252
  bigEndian: field.swapped === true,
253
+ boolean: field.type?._isBoolean === true,
249
254
  });
250
255
  field.readBits = read;
251
- field.writeBits = write;
256
+ field.writeBits = simpleFieldWriter(field.type, (buf, offset, value) => write(buf, value), 0);
252
257
  fieldReaders[name] = read;
253
- fieldWriters[name] = write;
258
+ fieldWriters[name] = field.writeBits;
254
259
  continue;
255
260
  }
256
261
 
@@ -264,12 +269,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
264
269
  const fieldOffset = offset;
265
270
  const ptrType = field.type;
266
271
  if (is64) {
267
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset));
272
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset), buf, fieldOffset);
268
273
  fieldWriters[name] = (buf, val) => {
269
274
  writePointerField(buf, fieldOffset, val, 8);
270
275
  };
271
276
  } else {
272
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)));
277
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)), buf, fieldOffset);
273
278
  fieldWriters[name] = (buf, val) => {
274
279
  writePointerField(buf, fieldOffset, val, 4);
275
280
  };
@@ -282,7 +287,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
282
287
  const fieldType = field.type;
283
288
  if (fieldType && fieldType._isSimpleCData) {
284
289
  const fieldOffset = offset; // Capture offset for closure
285
- const reader = field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
290
+ const reader = scalarReader(fieldType, field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader, field.swapped);
286
291
  const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
287
292
  fieldReaders[name] = (buf) => reader(buf, fieldOffset);
288
293
  fieldWriters[name] = simpleFieldWriter(fieldType, writer, fieldOffset);
@@ -409,7 +414,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
409
414
  // POINTER() field — return PointerInstance
410
415
  if (field.isPointer) {
411
416
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
412
- return pointerOrNull(field.type, addr);
417
+ return pointerOrNull(field.type, addr, buf, field.offset);
413
418
  }
414
419
 
415
420
  // Array field (Python: c_char * n / c_wchar * n si leggono come stringa)
@@ -488,11 +493,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
488
493
 
489
494
  // Nested struct (senza dot = imposta da oggetto)
490
495
  if (field.isNested) {
491
- if (Buffer.isBuffer(value)) {
492
- value.copy(buf, field.offset, 0, field.size);
493
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
496
+ if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
494
497
  // Istanza struct/union: copia dei byte (Python), non campo per campo
495
- copyInstance(buf, field.offset, field.size, value);
498
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
496
499
  } else if (typeof value === "object") {
497
500
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
498
501
  for (const [k, v] of Object.entries(value)) {
@@ -513,8 +516,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
513
516
  // Python: bytes / str con il controllo di lunghezza ("bytes too long").
514
517
  if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
515
518
  field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
516
- } else if (Buffer.isBuffer(value)) {
517
- value.copy(buf, field.offset, 0, field.size);
519
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
520
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
518
521
  } else if (Array.isArray(value)) {
519
522
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
520
523
  const wrapped = field.type.wrap(arrayBuf);
@@ -565,12 +568,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
565
568
  // Accesso a campo annidato singolo
566
569
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
567
570
  field.type.set(nestedBuf, parts.slice(1).join("."), value);
568
- } else if (Buffer.isBuffer(value)) {
569
- // Copia buffer
570
- value.copy(buf, field.offset, 0, field.size);
571
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
571
+ } else if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
572
572
  // Istanza struct/union: copia dei byte (Python), non campo per campo
573
- copyInstance(buf, field.offset, field.size, value);
573
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
574
574
  } else if (typeof value === "object") {
575
575
  // Imposta campi da oggetto
576
576
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -585,9 +585,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
585
585
  if (field.isArray) {
586
586
  if (field.type._charKind !== undefined && typeof value === "string") {
587
587
  field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
588
- } else if (Buffer.isBuffer(value)) {
589
- // Copia buffer array
590
- value.copy(buf, field.offset, 0, field.size);
588
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
589
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
591
590
  } else if (Array.isArray(value)) {
592
591
  // Inizializza da array JavaScript
593
592
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -645,7 +644,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
645
644
  }
646
645
  } else if (field.isPointer) {
647
646
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
648
- result[field.name] = pointerOrNull(field.type, addr);
647
+ result[field.name] = pointerOrNull(field.type, addr, buf, field.offset);
649
648
  } else if (field.isArray) {
650
649
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
651
650
  result[field.name] = field.type._charKind !== undefined ? field.type.getValue(arrayBuf) : field.type.wrap(arrayBuf);
@@ -35,10 +35,10 @@
35
35
  */
36
36
 
37
37
  import { bitFieldAccessors } from "./bitfield.js";
38
- import { computeLayout, isGccLayout } from "./layout.js";
38
+ import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
39
39
  import { buildWrapper } from "./wrap.js";
40
40
  import { syncDefinition } from "../../memory/mirror.js";
41
- import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWriter, writePointerField } from "./common.js";
41
+ import { clearKeepAlives, copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
42
42
 
43
43
  /**
44
44
  * Creates a union type definition where all fields share offset 0.
@@ -90,7 +90,10 @@ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWrit
90
90
  * ```
91
91
  */
92
92
  // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
93
- const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fromAddress(address));
93
+ const pointerOrNull = (ptrType, address, buf, offset) => {
94
+ const owner = pointerOwner(buf, offset, address);
95
+ return address === 0n ? null : ptrType.fromAddress(address, owner);
96
+ };
94
97
 
95
98
  export function union(fields, options, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
96
99
  // Backward-compat: legacy positional signature (fields, sizeof, alloc, ...)
@@ -111,8 +114,8 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
111
114
  options = options || {};
112
115
  const swapped = options.swapped === true;
113
116
  // Python _pack_: `pack` da solo, o `packed: true` (= pack 1).
114
- const packValue = typeof options.pack === "number" ? options.pack : options.packed ? 1 : 0;
115
- const gccLayout = isGccLayout(options.layout, packValue);
117
+ const packValue = normalizePack(options.pack ?? (options.packed ? 1 : 0));
118
+ const gccLayout = isGccLayout(options.layout, packValue, options.pack != null || options.packed === true);
116
119
  const base = options.base ?? null;
117
120
  const fieldDefs = base ? base.fields.map((f) => ({ ...f })) : [];
118
121
  const ownDefs = [];
@@ -159,6 +162,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
159
162
  }
160
163
  // Array type: alignment == element alignment (C standard)
161
164
  else if (_isArrayType(type)) {
165
+ if (swapped) fieldDef.type = type._swappedType ?? type;
162
166
  size = type.getSize();
163
167
  alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(sizeof(type.elementType), native.POINTER_SIZE);
164
168
  fieldDef.isArray = true;
@@ -225,6 +229,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
225
229
  // generico.
226
230
  const fieldReaders = Object.create(null);
227
231
  const fieldWriters = Object.create(null);
232
+ const mayKeepObjects = fieldDefs.some((field) => field.isPointer || field.type?._isPointerValued || field.isNested || field.isArray);
228
233
  // Risolvi POINTER_SIZE una sola volta (costante di processo).
229
234
  const is64 = native.POINTER_SIZE === 8;
230
235
  for (const field of fieldDefs) {
@@ -241,22 +246,23 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
241
246
  bitSize: field.bitSize,
242
247
  signed: field.type?._signed === true,
243
248
  bigEndian: field.swapped === true,
249
+ boolean: field.type?._isBoolean === true,
244
250
  });
245
251
  field.readBits = read;
246
- field.writeBits = write;
252
+ field.writeBits = simpleFieldWriter(field.type, (buf, offset, value) => write(buf, value), 0);
247
253
  fieldReaders[name] = read;
248
- fieldWriters[name] = write;
254
+ fieldWriters[name] = field.writeBits;
249
255
  continue;
250
256
  }
251
257
  if (field.isPointer) {
252
258
  const ptrType = field.type;
253
259
  if (is64) {
254
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(offset));
260
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(offset), buf, offset);
255
261
  fieldWriters[name] = (buf, val) => {
256
262
  writePointerField(buf, offset, val, 8);
257
263
  };
258
264
  } else {
259
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(offset)));
265
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(offset)), buf, offset);
260
266
  fieldWriters[name] = (buf, val) => {
261
267
  writePointerField(buf, offset, val, 4);
262
268
  };
@@ -266,11 +272,18 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
266
272
 
267
273
  const fieldType = field.type;
268
274
  if (fieldType && fieldType._isSimpleCData) {
269
- const reader = field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
275
+ const reader = scalarReader(fieldType, field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader, field.swapped);
270
276
  const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
271
277
  if (reader && writer) {
272
278
  fieldReaders[name] = (buf) => reader(buf, offset);
273
- fieldWriters[name] = simpleFieldWriter(fieldType, writer, offset);
279
+ const write = simpleFieldWriter(fieldType, writer, offset);
280
+ fieldWriters[name] =
281
+ mayKeepObjects && !fieldType._isPointerValued
282
+ ? (buf, value) => {
283
+ write(buf, value);
284
+ clearKeepAlives(buf, offset, fieldType._size);
285
+ }
286
+ : write;
274
287
  }
275
288
  }
276
289
  }
@@ -428,7 +441,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
428
441
  // POINTER() field — return PointerInstance
429
442
  if (field.isPointer) {
430
443
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
431
- return pointerOrNull(field.type, addr);
444
+ return pointerOrNull(field.type, addr, buf, field.offset);
432
445
  }
433
446
 
434
447
  // Tipo base: stesso accessor del fast path (rispetta l'endianness)
@@ -465,11 +478,9 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
465
478
 
466
479
  // Nested struct
467
480
  if (field.isNested) {
468
- if (Buffer.isBuffer(value)) {
469
- value.copy(buf, field.offset, 0, field.size);
470
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
481
+ if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
471
482
  // Istanza struct/union: copia dei byte (Python), non campo per campo
472
- copyInstance(buf, field.offset, field.size, value);
483
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
473
484
  } else if (typeof value === "object") {
474
485
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
475
486
  for (const [k, v] of Object.entries(value)) {
@@ -484,16 +495,13 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
484
495
  // Python: bytes / str con il controllo di lunghezza ("bytes too long").
485
496
  if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
486
497
  field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
487
- } else if (Buffer.isBuffer(value)) {
488
- value.copy(buf, field.offset, 0, field.size);
498
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
499
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
489
500
  } else if (Array.isArray(value)) {
490
501
  const wrapped = field.type.wrap(buf.subarray(field.offset, field.offset + field.size));
491
502
  for (let i = 0; i < Math.min(value.length, field.type.length); i++) {
492
503
  wrapped[i] = value[i];
493
504
  }
494
- } else if (value && value._buffer && Buffer.isBuffer(value._buffer)) {
495
- // Handle array proxy instances
496
- value._buffer.copy(buf, field.offset, 0, field.size);
497
505
  }
498
506
  return;
499
507
  }
@@ -560,7 +568,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
560
568
  return [...wrapped];
561
569
  } else if (field.isPointer) {
562
570
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(0) : BigInt(buf.readUInt32LE(0));
563
- return pointerOrNull(field.type, addr);
571
+ return pointerOrNull(field.type, addr, buf, 0);
564
572
  } else {
565
573
  return fieldReaders[field.name](buf);
566
574
  }
@@ -568,6 +576,8 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
568
576
  set(value) {
569
577
  if (field.isBitField) {
570
578
  field.writeBits(buf, value);
579
+ } else if (field.isArray) {
580
+ unionDef.set(buf, field.name, value);
571
581
  } else if (field.isPointer) {
572
582
  writePointerField(buf, 0, value, native.POINTER_SIZE);
573
583
  } else {
@@ -46,7 +46,7 @@
46
46
  * ```
47
47
  */
48
48
 
49
- import { kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive } from "../memory/mirror.js";
49
+ import { copyInstance, inDllBuffer, scalarOutparam, scalarView, sourceBytes } from "../structures/helpers/common.js";
50
50
 
51
51
  /**
52
52
  * Creates the SimpleCData base class with required dependencies injected.
@@ -56,16 +56,6 @@ import { kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive } from "../me
56
56
  * @private
57
57
  */
58
58
  export function createSimpleCDataClass(alloc, ptrToBuffer) {
59
- // Istanza su un Buffer esistente. Su una copia di memoria nativa (Electron,
60
- // memory/mirror.js) `value` resta sincronizzato con la memoria.
61
- function withBuffer(Ctor, buf) {
62
- const base = mirrorsActive ? mirrorBase(buf) : undefined;
63
- const inst = Object.create(base === undefined ? Ctor.prototype : mirroredPrototype(Ctor));
64
- inst._buffer = buf;
65
- if (base !== undefined) inst[kMirrorBase] = base;
66
- return inst;
67
- }
68
-
69
59
  /**
70
60
  * SimpleCData base class for primitive C types.
71
61
  *
@@ -119,7 +109,7 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
119
109
  constructor(value) {
120
110
  const Ctor = this.constructor;
121
111
  this._buffer = alloc(Ctor._size);
122
- if (value !== undefined && value !== null) {
112
+ if (value !== undefined) {
123
113
  this.value = value;
124
114
  }
125
115
  }
@@ -155,10 +145,8 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
155
145
  * @returns {SimpleCData} New instance wrapping the buffer slice
156
146
  */
157
147
  static from_buffer(buffer, offset = 0) {
158
- if (!Buffer.isBuffer(buffer)) {
159
- throw new TypeError("from_buffer requires a Buffer");
160
- }
161
- return withBuffer(this, buffer.subarray(offset, offset + this._size));
148
+ const bytes = sourceBytes(buffer, offset, this._size, "from_buffer");
149
+ return scalarView(this, Buffer.isBuffer(bytes) ? bytes.subarray(offset, offset + this._size) : Buffer.from(bytes.buffer, bytes.byteOffset + offset, this._size));
162
150
  }
163
151
 
164
152
  /**
@@ -168,12 +156,10 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
168
156
  * @returns {SimpleCData} New instance with copied data
169
157
  */
170
158
  static from_buffer_copy(buffer, offset = 0) {
171
- if (!Buffer.isBuffer(buffer)) {
172
- throw new TypeError("from_buffer_copy requires a Buffer");
173
- }
174
- const inst = new this();
175
- buffer.copy(inst._buffer, 0, offset, offset + this._size);
176
- return inst;
159
+ const bytes = sourceBytes(buffer, offset, this._size, "from_buffer_copy");
160
+ const copy = alloc(this._size);
161
+ copyInstance(copy, 0, this._size, bytes, offset, this);
162
+ return scalarView(this, copy);
177
163
  }
178
164
 
179
165
  /**
@@ -188,7 +174,7 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
188
174
  throw new Error("from_address requires ptrToBuffer injected at construction");
189
175
  }
190
176
  const addr = typeof address === "bigint" ? address : BigInt(address);
191
- return withBuffer(this, ptrToBuffer(addr, this._size));
177
+ return scalarView(this, ptrToBuffer(addr, this._size));
192
178
  }
193
179
 
194
180
  /**
@@ -206,15 +192,7 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
206
192
  * @returns {SimpleCData} Instance whose buffer aliases the symbol's memory
207
193
  */
208
194
  static in_dll(library, name) {
209
- const nativeLib = library && library._lib ? library._lib : library;
210
- if (!nativeLib || typeof nativeLib.symbol !== "function") {
211
- throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
212
- }
213
- const addr = nativeLib.symbol(name);
214
- if (!addr) {
215
- throw new Error(`in_dll: symbol '${name}' not found`);
216
- }
217
- return this.from_address(addr);
195
+ return scalarView(this, inDllBuffer(library, name, this._size, ptrToBuffer));
218
196
  }
219
197
 
220
198
  /**
@@ -239,6 +217,7 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
239
217
  }
240
218
 
241
219
  SimpleCData._isSimpleCData = true;
220
+ Object.defineProperty(SimpleCData.prototype, "__ctypes_from_outparam__", { value: scalarOutparam, writable: true, configurable: true });
242
221
 
243
222
  // Marcatore per riconoscere le istanze (es. negli argomenti di funzione) con
244
223
  // un semplice accesso a proprietà, senza instanceof né `constructor`.
@@ -60,7 +60,7 @@
60
60
  * ```
61
61
  */
62
62
 
63
- import { keepAlive, notIntegral } from "../structures/helpers/common.js";
63
+ import { booleanValue, keepAlive, notIntegral, registerSimpleType } from "../structures/helpers/common.js";
64
64
 
65
65
  /**
66
66
  * Creates all primitive type classes with required dependencies injected.
@@ -107,9 +107,22 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
107
107
  // double), BigInt via asIntN/asUintN.
108
108
  // Il caso number è testato per primo: è il percorso caldo dei campi.
109
109
  // Un number non intero è un float, che Python rifiuta per i tipi interi.
110
- const u32 = (val) => (typeof val === "number" ? (Number.isInteger(val) ? val >>> 0 : notIntegral()) : typeof val === "bigint" ? Number(BigInt.asUintN(32, val)) : val >>> 0);
111
- const i32 = (val) => (typeof val === "number" ? (Number.isInteger(val) ? val | 0 : notIntegral()) : typeof val === "bigint" ? Number(BigInt.asIntN(32, val)) : val | 0);
112
- const u64 = (val) => BigInt.asUintN(64, typeof val === "bigint" ? val : typeof val === "number" && !Number.isInteger(val) ? notIntegral() : BigInt(val));
110
+ const integerBoolean = (val) => {
111
+ if (typeof val === "boolean") return +val;
112
+ throw new TypeError(`'${typeName(val)}' object cannot be interpreted as an integer`);
113
+ };
114
+ const u32 = (val) => (typeof val === "number" ? (Number.isInteger(val) ? val >>> 0 : notIntegral()) : typeof val === "bigint" ? Number(BigInt.asUintN(32, val)) : integerBoolean(val));
115
+ const i32 = (val) => (typeof val === "number" ? (Number.isInteger(val) ? val | 0 : notIntegral()) : typeof val === "bigint" ? Number(BigInt.asIntN(32, val)) : integerBoolean(val));
116
+ const u64 = (val) => BigInt.asUintN(64, typeof val === "bigint" ? val : typeof val === "number" ? (Number.isInteger(val) ? BigInt(val) : notIntegral()) : BigInt(integerBoolean(val)));
117
+ const real = (val) => {
118
+ if (typeof val === "number") return val;
119
+ if (typeof val === "boolean") return +val;
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);
123
+ }
124
+ throw new TypeError(`must be real number, not ${typeName(val)}`);
125
+ };
113
126
  const writeU8 = (buf, off, val) => {
114
127
  buf[off] = u32(val);
115
128
  };
@@ -226,18 +239,18 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
226
239
  static _size = 4;
227
240
  static _type = CType.FLOAT;
228
241
  static _reader = (buf, off) => buf.readFloatLE(off);
229
- static _writer = (buf, off, val) => buf.writeFloatLE(val, off);
242
+ static _writer = (buf, off, val) => buf.writeFloatLE(real(val), off);
230
243
  static _readerBE = (buf, off) => buf.readFloatBE(off);
231
- static _writerBE = (buf, off, val) => buf.writeFloatBE(val, off);
244
+ static _writerBE = (buf, off, val) => buf.writeFloatBE(real(val), off);
232
245
  }
233
246
 
234
247
  class c_double extends SimpleCData {
235
248
  static _size = 8;
236
249
  static _type = CType.DOUBLE;
237
250
  static _reader = (buf, off) => buf.readDoubleLE(off);
238
- static _writer = (buf, off, val) => buf.writeDoubleLE(val, off);
251
+ static _writer = (buf, off, val) => buf.writeDoubleLE(real(val), off);
239
252
  static _readerBE = (buf, off) => buf.readDoubleBE(off);
240
- static _writerBE = (buf, off, val) => buf.writeDoubleBE(val, off);
253
+ static _writerBE = (buf, off, val) => buf.writeDoubleBE(real(val), off);
241
254
  }
242
255
 
243
256
  // ============================================================================
@@ -247,8 +260,9 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
247
260
  class c_bool extends SimpleCData {
248
261
  static _size = 1;
249
262
  static _type = CType.BOOL;
263
+ static _isBoolean = true;
250
264
  static _reader = (buf, off) => buf.readUInt8(off) !== 0;
251
- static _writer = (buf, off, val) => buf.writeUInt8(val ? 1 : 0, off);
265
+ static _writer = (buf, off, val) => buf.writeUInt8(booleanValue(val) ? 1 : 0, off);
252
266
  static _readerBE = c_bool._reader;
253
267
  static _writerBE = c_bool._writer;
254
268
  }
@@ -417,6 +431,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
417
431
  class c_ssize_t extends SimpleCData {
418
432
  static _size = native.POINTER_SIZE;
419
433
  static _type = CType.SSIZE_T;
434
+ static _signed = true;
420
435
  static _reader = (buf, off) => {
421
436
  return native.POINTER_SIZE === 8 ? buf.readBigInt64LE(off) : buf.readInt32LE(off);
422
437
  };
@@ -434,6 +449,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
434
449
  class c_long extends SimpleCData {
435
450
  static _size = _longSize;
436
451
  static _type = CType.LONG;
452
+ static _signed = true;
437
453
  static _reader = _longSize === 8 ? (buf, off) => buf.readBigInt64LE(off) : (buf, off) => BigInt(buf.readInt32LE(off));
438
454
  static _writer = writeWord(_longSize);
439
455
  static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigInt64BE(off) : (buf, off) => BigInt(buf.readInt32BE(off));
@@ -482,14 +498,14 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
482
498
  val = cstring(val);
483
499
  }
484
500
  if (Buffer.isBuffer(val)) {
485
- _stringKeepalive(buf, off, val);
486
501
  _writePointerField(buf, off, addressOf(val));
502
+ _stringKeepalive(buf, off, val);
487
503
  } else if (val == null) {
488
- _stringKeepalive(buf, off, null);
489
504
  _writePointerField(buf, off, 0n);
490
- } else {
491
505
  _stringKeepalive(buf, off, null);
506
+ } else {
492
507
  _writePointerField(buf, off, val);
508
+ _stringKeepalive(buf, off, null);
493
509
  }
494
510
  };
495
511
  }
@@ -508,14 +524,14 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
508
524
  val = wstring(val);
509
525
  }
510
526
  if (Buffer.isBuffer(val)) {
511
- _stringKeepalive(buf, off, val);
512
527
  _writePointerField(buf, off, addressOf(val));
528
+ _stringKeepalive(buf, off, val);
513
529
  } else if (val == null) {
514
- _stringKeepalive(buf, off, null);
515
530
  _writePointerField(buf, off, 0n);
516
- } else {
517
531
  _stringKeepalive(buf, off, null);
532
+ } else {
518
533
  _writePointerField(buf, off, val);
534
+ _stringKeepalive(buf, off, null);
519
535
  }
520
536
  };
521
537
  }
@@ -534,7 +550,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
534
550
  const c_ulonglong = c_uint64;
535
551
 
536
552
  // Return all types
537
- return {
553
+ const types = {
538
554
  // Void
539
555
  c_void,
540
556
  // Signed integers
@@ -574,4 +590,6 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
574
590
  c_longlong,
575
591
  c_ulonglong,
576
592
  };
593
+ for (const type of Object.values(types)) registerSimpleType(type);
594
+ return types;
577
595
  }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @file cache.js
3
3
  * @module utils/cache
4
- * @description Simple LRU (Least Recently Used) cache implementation for function caching.
5
- * Prevents unbounded memory growth in long-running applications.
4
+ * @description LRU function caching and weak-value type interning.
5
+ * Prevents unbounded cache retention in long-running applications.
6
6
  *
7
7
  * @example
8
8
  * import { LRUCache } from './utils/cache.js';
@@ -140,3 +140,35 @@ export class LRUCache {
140
140
  return this.cache.size;
141
141
  }
142
142
  }
143
+
144
+ const weakValues = new FinalizationRegistry(({ cache, key, ref }) => {
145
+ // A delayed finalizer must not remove a replacement for the same key.
146
+ if (cache.get(key) === ref) cache.delete(key);
147
+ });
148
+
149
+ /** Identity keys without retaining object/function types. */
150
+ export function createTypeKey() {
151
+ const identities = new WeakMap();
152
+ let next = 0;
153
+ return (type) => {
154
+ if (type === null || (typeof type !== "object" && typeof type !== "function")) {
155
+ const value = String(type);
156
+ return `${typeof type}:${value.length}:${value}`;
157
+ }
158
+ let id = identities.get(type);
159
+ if (id === undefined) {
160
+ id = `#${++next}`;
161
+ identities.set(type, id);
162
+ }
163
+ return id;
164
+ };
165
+ }
166
+
167
+ /** Store a weak value in a Map and remove its key when the value is collected. */
168
+ export function cacheWeakValue(cache, key, value) {
169
+ const previous = cache.get(key);
170
+ const ref = new WeakRef(value);
171
+ if (previous !== undefined) weakValues.unregister(previous);
172
+ cache.set(key, ref);
173
+ weakValues.register(value, { cache, key, ref }, ref);
174
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",
@@ -32,6 +32,8 @@
32
32
  "clean": "cmake-js clean",
33
33
  "generate-ffi-headers": "node third-party/libffi_cmake/generate-headers.js",
34
34
  "test:types": "tsc -p tests/types/tsconfig.json",
35
+ "bench:koffi": "node tests/benchmarks/benchmark_koffi.js",
36
+ "bench:ffi": "node --experimental-ffi tests/benchmarks/benchmark_node_ffi.js",
35
37
  "docs": "typedoc",
36
38
  "docs:serve": "typedoc && npx serve docs"
37
39
  },