node-ctypes 2.3.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.
@@ -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 = [];
@@ -132,7 +135,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
132
135
  fieldDef.cls = type.cls;
133
136
  if (typeof def === "function" && typeof def._buildStruct === "function") {
134
137
  fieldDef.cls = def;
135
- def = def._structDef || def._buildStruct();
138
+ def = def._finalizeFields();
136
139
  }
137
140
  if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
138
141
  throw new TypeError(`anonymous field "${name}" must be a structure or union`);
@@ -144,11 +147,11 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
144
147
  alignment = def.alignment;
145
148
  }
146
149
  // Nested struct (object form or class form)
147
- else if (_isStruct(type)) {
150
+ else if ((typeof type === "function" && type.prototype instanceof Structure) || _isStruct(type)) {
148
151
  // Normalize type: if it's a Structure/Union class, get its _structDef
149
152
  let nestedStruct = type;
150
153
  if (typeof type === "function" && typeof type._buildStruct === "function") {
151
- nestedStruct = type._structDef || type._buildStruct();
154
+ nestedStruct = type._finalizeFields();
152
155
  fieldDef.type = nestedStruct;
153
156
  // Python restituisce un'istanza della classe annidata.
154
157
  fieldDef.cls = type;
@@ -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
  }
@@ -313,7 +326,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
313
326
 
314
327
  // Prima imposta i campi diretti
315
328
  for (const field of fieldDefs) {
316
- if (values[field.name] !== undefined) {
329
+ if (Object.hasOwn(values, field.name) && values[field.name] !== undefined) {
317
330
  unionDef.set(buf, field.name, values[field.name]);
318
331
  }
319
332
  }
@@ -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,23 @@ 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
+ const number = Number(val);
122
+ if (!Number.isFinite(number)) throw new RangeError("int too large to convert to float");
123
+ return number;
124
+ }
125
+ throw new TypeError(`must be real number, not ${typeName(val)}`);
126
+ };
113
127
  const writeU8 = (buf, off, val) => {
114
128
  buf[off] = u32(val);
115
129
  };
@@ -226,18 +240,18 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
226
240
  static _size = 4;
227
241
  static _type = CType.FLOAT;
228
242
  static _reader = (buf, off) => buf.readFloatLE(off);
229
- static _writer = (buf, off, val) => buf.writeFloatLE(val, off);
243
+ static _writer = (buf, off, val) => buf.writeFloatLE(real(val), off);
230
244
  static _readerBE = (buf, off) => buf.readFloatBE(off);
231
- static _writerBE = (buf, off, val) => buf.writeFloatBE(val, off);
245
+ static _writerBE = (buf, off, val) => buf.writeFloatBE(real(val), off);
232
246
  }
233
247
 
234
248
  class c_double extends SimpleCData {
235
249
  static _size = 8;
236
250
  static _type = CType.DOUBLE;
237
251
  static _reader = (buf, off) => buf.readDoubleLE(off);
238
- static _writer = (buf, off, val) => buf.writeDoubleLE(val, off);
252
+ static _writer = (buf, off, val) => buf.writeDoubleLE(real(val), off);
239
253
  static _readerBE = (buf, off) => buf.readDoubleBE(off);
240
- static _writerBE = (buf, off, val) => buf.writeDoubleBE(val, off);
254
+ static _writerBE = (buf, off, val) => buf.writeDoubleBE(real(val), off);
241
255
  }
242
256
 
243
257
  // ============================================================================
@@ -247,8 +261,9 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
247
261
  class c_bool extends SimpleCData {
248
262
  static _size = 1;
249
263
  static _type = CType.BOOL;
264
+ static _isBoolean = true;
250
265
  static _reader = (buf, off) => buf.readUInt8(off) !== 0;
251
- static _writer = (buf, off, val) => buf.writeUInt8(val ? 1 : 0, off);
266
+ static _writer = (buf, off, val) => buf.writeUInt8(booleanValue(val) ? 1 : 0, off);
252
267
  static _readerBE = c_bool._reader;
253
268
  static _writerBE = c_bool._writer;
254
269
  }
@@ -417,6 +432,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
417
432
  class c_ssize_t extends SimpleCData {
418
433
  static _size = native.POINTER_SIZE;
419
434
  static _type = CType.SSIZE_T;
435
+ static _signed = true;
420
436
  static _reader = (buf, off) => {
421
437
  return native.POINTER_SIZE === 8 ? buf.readBigInt64LE(off) : buf.readInt32LE(off);
422
438
  };
@@ -434,6 +450,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
434
450
  class c_long extends SimpleCData {
435
451
  static _size = _longSize;
436
452
  static _type = CType.LONG;
453
+ static _signed = true;
437
454
  static _reader = _longSize === 8 ? (buf, off) => buf.readBigInt64LE(off) : (buf, off) => BigInt(buf.readInt32LE(off));
438
455
  static _writer = writeWord(_longSize);
439
456
  static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigInt64BE(off) : (buf, off) => BigInt(buf.readInt32BE(off));
@@ -482,14 +499,14 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
482
499
  val = cstring(val);
483
500
  }
484
501
  if (Buffer.isBuffer(val)) {
485
- _stringKeepalive(buf, off, val);
486
502
  _writePointerField(buf, off, addressOf(val));
503
+ _stringKeepalive(buf, off, val);
487
504
  } else if (val == null) {
488
- _stringKeepalive(buf, off, null);
489
505
  _writePointerField(buf, off, 0n);
490
- } else {
491
506
  _stringKeepalive(buf, off, null);
507
+ } else {
492
508
  _writePointerField(buf, off, val);
509
+ _stringKeepalive(buf, off, null);
493
510
  }
494
511
  };
495
512
  }
@@ -508,14 +525,14 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
508
525
  val = wstring(val);
509
526
  }
510
527
  if (Buffer.isBuffer(val)) {
511
- _stringKeepalive(buf, off, val);
512
528
  _writePointerField(buf, off, addressOf(val));
529
+ _stringKeepalive(buf, off, val);
513
530
  } else if (val == null) {
514
- _stringKeepalive(buf, off, null);
515
531
  _writePointerField(buf, off, 0n);
516
- } else {
517
532
  _stringKeepalive(buf, off, null);
533
+ } else {
518
534
  _writePointerField(buf, off, val);
535
+ _stringKeepalive(buf, off, null);
519
536
  }
520
537
  };
521
538
  }
@@ -534,7 +551,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
534
551
  const c_ulonglong = c_uint64;
535
552
 
536
553
  // Return all types
537
- return {
554
+ const types = {
538
555
  // Void
539
556
  c_void,
540
557
  // Signed integers
@@ -574,4 +591,6 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
574
591
  c_longlong,
575
592
  c_ulonglong,
576
593
  };
594
+ for (const type of Object.values(types)) registerSimpleType(type);
595
+ return types;
577
596
  }
@@ -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.5.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
  },