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
Binary file
Binary file
@@ -40,7 +40,8 @@
40
40
  */
41
41
 
42
42
  import { _toNativeReturnType } from "./types.js";
43
- import { adaptCallbackFunction, argumentConverters, convertArguments, coerceValue, resultConverter } from "./conversions.js";
43
+ import { adaptCallbackFunction, argumentConverters, argumentsNeedOwners, callWithArgumentOwners, callWithResultHandler, convertArguments, needsArgumentOwners, resultCheck, resultConverter, scalarResult, structResult } from "./conversions.js";
44
+ import { createTypeKey } from "../utils/cache.js";
44
45
 
45
46
  /**
46
47
  * Creates the Library-related classes with required dependencies injected.
@@ -54,30 +55,38 @@ import { adaptCallbackFunction, argumentConverters, convertArguments, coerceValu
54
55
  * @private
55
56
  */
56
57
  export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNativeTypes, native) {
57
- // Chiave di cache di un tipo: i tipi oggetto/classe (POINTER, struct, ...) hanno
58
- // un id stabile; `${tipo}` darebbe "[object Object]" per tutti i POINTER.
59
- const typeIds = new WeakMap();
60
- let nextTypeId = 0;
61
- const typeKey = (t) => {
62
- if (t === null || (typeof t !== "object" && typeof t !== "function")) return String(t);
63
- let id = typeIds.get(t);
64
- if (id === undefined) {
65
- id = `#${++nextTypeId}`;
66
- typeIds.set(t, id);
58
+ const typeKey = createTypeKey();
59
+ // Funzione passata a errcheck quando la chiamata passa da un attributo
60
+ // della libreria (FunctionWrapper).
61
+ const kErrcheckFunc = Symbol("errcheckFunc");
62
+
63
+ // Chiave di cache delle opzioni di func() (abi, ...), indipendente dall'ordine.
64
+ const optionsKey = (options) => {
65
+ let key = "";
66
+ for (const name of Object.keys(options).sort()) {
67
+ key += `;${name}=${typeKey(options[name])}`;
67
68
  }
68
- return id;
69
+ return key;
69
70
  };
70
71
 
71
72
  class FunctionWrapper {
72
73
  constructor(cdll, name) {
73
74
  const argtypes = [];
74
75
  let restype = undefined;
76
+ let errcheck = null;
75
77
  let cachedFunc = null;
76
78
 
77
- // Python ctypes: restype predefinito c_int.
79
+ // Python ctypes: restype predefinito c_int. Ogni attributo (libc.abs) ha
80
+ // la sua funzione, non quella condivisa dalla cache di func(): errcheck
81
+ // non tocca altri utenti della stessa firma e resta dopo un cambio di
82
+ // argtypes / restype, come in Python.
78
83
  const resolve = () => {
79
84
  if (!cachedFunc) {
80
- cachedFunc = cdll.func(name, restype === undefined ? FunctionWrapper.defaultRestype : restype, argtypes);
85
+ cachedFunc = cdll._createFunction(name, restype === undefined ? cdll._defaultRestype() : restype, argtypes);
86
+ Object.defineProperty(cachedFunc, kErrcheckFunc, { value: func });
87
+ if (errcheck !== null) {
88
+ cachedFunc.errcheck = errcheck;
89
+ }
81
90
  }
82
91
  return cachedFunc;
83
92
  };
@@ -87,16 +96,19 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
87
96
  const func = (...args) => (cachedFunc ?? resolve())(...args);
88
97
 
89
98
  Object.defineProperties(func, {
99
+ address: { get: () => resolve().address },
100
+ _as_parameter_: { get: () => resolve().address },
90
101
  argtypes: {
91
102
  get: () => argtypes,
92
103
  set: (value) => {
93
- argtypes.splice(0, argtypes.length, ...value);
104
+ // Python: argtypes = None toglie i tipi degli argomenti.
105
+ argtypes.splice(0, argtypes.length, ...(value ?? []));
94
106
  cachedFunc = null; // Invalidate cache
95
107
  },
96
108
  configurable: true,
97
109
  },
98
110
  restype: {
99
- get: () => (restype === undefined ? FunctionWrapper.defaultRestype : restype),
111
+ get: () => (restype === undefined ? cdll._defaultRestype() : restype),
100
112
  set: (value) => {
101
113
  restype = value;
102
114
  cachedFunc = null; // Invalidate cache
@@ -104,9 +116,13 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
104
116
  configurable: true,
105
117
  },
106
118
  errcheck: {
107
- get: () => (cachedFunc ? cachedFunc.errcheck : null),
119
+ get: () => errcheck,
108
120
  set: (value) => {
109
- resolve().errcheck = value;
121
+ if (value !== null && value !== undefined && typeof value !== "function") throw new TypeError("errcheck must be a function or null");
122
+ errcheck = value ?? null;
123
+ if (cachedFunc) {
124
+ cachedFunc.errcheck = errcheck;
125
+ }
110
126
  },
111
127
  configurable: true,
112
128
  },
@@ -131,7 +147,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
131
147
  if (typeof options === "number") {
132
148
  options = { mode: options };
133
149
  }
134
- this._lib = options.mode === undefined ? new Library(libPath) : new Library(libPath, options.mode);
150
+ this._lib = new Library(libPath, options.mode, options.winmode);
135
151
  // Use LRU cache to prevent unbounded memory growth
136
152
  const cacheSize = options.cacheSize ?? 1000;
137
153
  this._cache = new LRUCache(cacheSize);
@@ -171,18 +187,41 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
171
187
  * @param {Object} [options] - Opzioni aggiuntive (es. { abi: 'stdcall' })
172
188
  * @returns {Function} Funzione callable
173
189
  */
174
- func(name, returnType, argTypes = [], options = {}) {
175
- const cacheKey = `${name}:${typeKey(returnType)}:${argTypes.map(typeKey).join(",")}`;
190
+ _defaultRestype() {
191
+ return FunctionWrapper.defaultRestype;
192
+ }
176
193
 
177
- if (this._cache.has(cacheKey)) {
178
- return this._cache.get(cacheKey);
194
+ func(name, returnType = this._defaultRestype(), argTypes = [], options = {}) {
195
+ const cacheKey = `${name}:${typeKey(returnType)}:${argTypes.map(typeKey).join(",")}${optionsKey(options)}`;
196
+ let fn = this._cache.get(cacheKey);
197
+ if (fn === undefined) {
198
+ fn = this._createFunction(name, returnType, argTypes, options);
199
+ this._cache.set(cacheKey, fn);
179
200
  }
201
+ return fn;
202
+ }
180
203
 
204
+ /**
205
+ * Controllo del risultato prima di errcheck (Python: `_check_retval_` del
206
+ * restype, es. HRESULT in OleDLL). undefined se non c'è.
207
+ * @protected
208
+ */
209
+ _resultCheck(returnType, name) {
210
+ return resultCheck(returnType, name, this.constructor.name);
211
+ }
212
+
213
+ /**
214
+ * Crea una nuova funzione, senza cache (vedi func()).
215
+ * @protected
216
+ */
217
+ _createFunction(name, returnType, argTypes = [], options = {}) {
181
218
  // Propagate library-level use_last_error / use_errno to the FFIFunction
182
219
  const mergedOptions = {
183
220
  ...options,
184
221
  ...(this._use_last_error ? { use_last_error: true } : {}),
185
222
  ...(this._use_errno ? { use_errno: true } : {}),
223
+ ...(structResult(returnType) ? { struct_buffer: true } : {}),
224
+ ...(scalarResult(returnType) ? { scalar_buffer: true } : {}),
186
225
  };
187
226
  const ffiFunc = this._lib.func(name, _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), mergedOptions);
188
227
 
@@ -193,81 +232,85 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
193
232
 
194
233
  const argCount = argTypes.length;
195
234
 
196
- // Check if any argtype defines a `from_param` classmethod. When true,
197
- // every call-site must route through a preprocessing pass that lets
198
- // user-defined types convert incoming values. This mirrors Python
199
- // ctypes' from_param protocol.
200
- const anyFromParam = argTypes.some((t) => t && typeof t === "function" && typeof t.from_param === "function");
201
-
202
- // Helper: apply Python ctypes _as_parameter_ / from_param protocols.
203
- // Used only in the slow path (anyFromParam = true).
204
- const applyParamProtocols = (arg, i) => {
205
- if (arg && typeof arg === "object" && arg._as_parameter_ !== undefined) {
206
- arg = arg._as_parameter_;
207
- }
208
- if (i < argCount) {
209
- const t = argTypes[i];
210
- if (t && typeof t === "function" && typeof t.from_param === "function") {
211
- arg = t.from_param(arg);
212
- if (arg && typeof arg === "object" && arg._as_parameter_ !== undefined) {
213
- arg = arg._as_parameter_;
214
- }
215
- }
216
- }
217
- return arg;
218
- };
219
-
220
235
  // Conversione degli argomenti come il from_param di base di Python
221
236
  // (vedi conversions.js): un convertitore per posizione dichiarata.
222
237
  const C = argumentConverters(argTypes, native);
223
238
  const [C0, C1, C2, C3, C4, C5] = C;
224
239
  const convertAll = (args) => convertArguments(args, C);
240
+ const hasAdapters = C.some((convert) => convert.requiresOwners);
241
+ const baseConvert = resultConverter(returnType);
242
+ const check = this._resultCheck(returnType, name);
243
+ const convertResult = check === undefined ? baseConvert : baseConvert === undefined ? check : (result) => check(baseConvert(result));
244
+ const captureHere = convertResult === undefined;
245
+ let jsErrcheck = null;
246
+ let checkedSync;
247
+ const checkedCall = (method, args, checked) => {
248
+ const originalArgs = Array.isArray(args) ? args : Array.prototype.slice.call(args);
249
+ const func = errcheckFunc();
250
+ const finish = (result) => checked(convertResult === undefined ? result : convertResult(result), func, originalArgs);
251
+ const call = method === "call" ? (checkedSync ??= ffiFunc._makeCheckedCall()) : undefined;
252
+ return callWithResultHandler(ffiFunc, method, originalArgs, C, finish, hasAdapters || argumentsNeedOwners(originalArgs), call);
253
+ };
254
+ const ownedCall = (method, args) => callWithArgumentOwners(ffiFunc, method, args, C);
255
+ const invoke = (method, args) => {
256
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, args, jsErrcheck);
257
+ return captureHere && (hasAdapters || argumentsNeedOwners(args)) ? ownedCall(method, args) : ffiFunc[method](...convertAll(args));
258
+ };
225
259
 
226
260
  // Funzioni specializzate per numero di argomenti (niente array per la
227
261
  // chiamata comune); `method` è "call" o "callAsync".
228
262
  const specialize = (method) => {
229
- if (anyFromParam) {
230
- // SLOW PATH: from_param su ogni argomento dichiarato.
231
- return function (...args) {
232
- const processedArgs = new Array(args.length);
233
- for (let i = 0; i < args.length; i++) {
234
- processedArgs[i] = i < argCount ? applyParamProtocols(C[i](args[i]), i) : coerceValue(args[i]);
235
- }
236
- return ffiFunc[method](...processedArgs);
237
- };
238
- }
239
263
  switch (argCount) {
240
264
  case 0:
241
265
  return function () {
242
- return arguments.length === 0 ? ffiFunc[method]() : ffiFunc[method](...convertAll(arguments));
266
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
267
+ return arguments.length === 0 ? ffiFunc[method]() : invoke(method, arguments);
243
268
  };
244
269
  case 1:
245
270
  return function (a0) {
246
- return arguments.length === 1 ? ffiFunc[method](C0(a0)) : ffiFunc[method](...convertAll(arguments));
271
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
272
+ if (arguments.length !== 1) return invoke(method, arguments);
273
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0))) return ownedCall(method, arguments);
274
+ return ffiFunc[method](C0(a0));
247
275
  };
248
276
  case 2:
249
277
  return function (a0, a1) {
250
- return arguments.length === 2 ? ffiFunc[method](C0(a0), C1(a1)) : ffiFunc[method](...convertAll(arguments));
278
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
279
+ if (arguments.length !== 2) return invoke(method, arguments);
280
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1))) return ownedCall(method, arguments);
281
+ return ffiFunc[method](C0(a0), C1(a1));
251
282
  };
252
283
  case 3:
253
284
  return function (a0, a1, a2) {
254
- return arguments.length === 3 ? ffiFunc[method](C0(a0), C1(a1), C2(a2)) : ffiFunc[method](...convertAll(arguments));
285
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
286
+ if (arguments.length !== 3) return invoke(method, arguments);
287
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2))) return ownedCall(method, arguments);
288
+ return ffiFunc[method](C0(a0), C1(a1), C2(a2));
255
289
  };
256
290
  case 4:
257
291
  return function (a0, a1, a2, a3) {
258
- return arguments.length === 4 ? ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3)) : ffiFunc[method](...convertAll(arguments));
292
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
293
+ if (arguments.length !== 4) return invoke(method, arguments);
294
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3))) return ownedCall(method, arguments);
295
+ return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3));
259
296
  };
260
297
  case 5:
261
298
  return function (a0, a1, a2, a3, a4) {
262
- return arguments.length === 5 ? ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4)) : ffiFunc[method](...convertAll(arguments));
299
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
300
+ if (arguments.length !== 5) return invoke(method, arguments);
301
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3) || needsArgumentOwners(a4))) return ownedCall(method, arguments);
302
+ return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4));
263
303
  };
264
304
  case 6:
265
305
  return function (a0, a1, a2, a3, a4, a5) {
266
- return arguments.length === 6 ? ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5)) : ffiFunc[method](...convertAll(arguments));
306
+ if (captureHere && jsErrcheck !== null) return checkedCall(method, arguments, jsErrcheck);
307
+ if (arguments.length !== 6) return invoke(method, arguments);
308
+ if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3) || needsArgumentOwners(a4) || needsArgumentOwners(a5))) return ownedCall(method, arguments);
309
+ return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5));
267
310
  };
268
311
  default:
269
312
  return function (...args) {
270
- return ffiFunc[method](...convertAll(args));
313
+ return invoke(method, args);
271
314
  };
272
315
  }
273
316
  };
@@ -275,22 +318,20 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
275
318
  let callMethod = specialize("call");
276
319
  let asyncCallMethod = specialize("callAsync");
277
320
 
278
- // Python: con restype POINTER(T) / CFUNCTYPE il risultato è un oggetto
279
- // puntatore / una funzione, ed errcheck riceve il valore già convertito:
280
- // in questo caso errcheck è applicato qui invece che nel nativo.
281
- const convertResult = resultConverter(returnType);
282
- let jsErrcheck = null;
321
+ // Result handlers run inside the native call scope, after conversion and
322
+ // with the hook/arguments captured before any argument adapter executes.
283
323
  if (convertResult !== undefined) {
284
324
  const rawCall = callMethod;
285
325
  const rawAsync = asyncCallMethod;
286
- const finish = (result, args) => {
287
- const converted = convertResult(result);
288
- return jsErrcheck === null ? converted : jsErrcheck(converted, callMethod, args);
289
- };
326
+ const finish = (result) => convertResult(result);
290
327
  callMethod = function (...args) {
328
+ if (jsErrcheck !== null) return checkedCall("call", args, jsErrcheck);
329
+ if (hasAdapters || argumentsNeedOwners(args)) return callWithArgumentOwners(ffiFunc, "call", args, C, finish);
291
330
  return finish(rawCall.apply(this, args), args);
292
331
  };
293
332
  asyncCallMethod = function (...args) {
333
+ if (jsErrcheck !== null) return checkedCall("callAsync", args, jsErrcheck);
334
+ if (hasAdapters || argumentsNeedOwners(args)) return callWithArgumentOwners(ffiFunc, "callAsync", args, C, finish);
294
335
  return rawAsync.apply(this, args).then((result) => finish(result, args));
295
336
  };
296
337
  }
@@ -311,31 +352,32 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
311
352
  };
312
353
  }
313
354
 
355
+ // Python: errcheck riceve la funzione su cui è impostato (l'attributo
356
+ // della libreria, se passa da lì), qualunque sia il restype.
357
+ const errcheckFunc = () => callMethod[kErrcheckFunc] ?? callMethod;
358
+
314
359
  // Aggiungi metadata come proprietà non-enumerable per non interferire
315
360
  Object.defineProperties(callMethod, {
316
361
  funcName: { value: name },
317
362
  address: { value: ffiFunc.address },
363
+ _as_parameter_: { value: ffiFunc.address },
318
364
  _ffi: { value: ffiFunc },
319
365
  callAsync: { value: asyncCallMethod, writable: false, enumerable: false, configurable: false },
320
366
  // Esponi errcheck come setter/getter
321
367
  errcheck: {
322
368
  get() {
323
- return ffiFunc._errcheck ?? null;
369
+ return jsErrcheck;
324
370
  },
325
371
  set(callback) {
326
- ffiFunc._errcheck = callback;
327
- if (convertResult !== undefined) {
328
- jsErrcheck = callback ?? null;
329
- } else {
330
- ffiFunc.setErrcheck(callback);
331
- }
372
+ callback = callback ?? null;
373
+ if (callback !== null && typeof callback !== "function") throw new TypeError("errcheck must be a function or null");
374
+ jsErrcheck = callback;
332
375
  },
333
376
  enumerable: false,
334
377
  configurable: true,
335
378
  },
336
379
  });
337
380
 
338
- this._cache.set(cacheKey, callMethod);
339
381
  return callMethod;
340
382
  }
341
383
 
@@ -356,7 +398,10 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
356
398
  * @returns {Object} Oggetto callback con proprietà pointer e metodi
357
399
  */
358
400
  callback(fn, returnType, argTypes = []) {
359
- return this._lib.callback(_toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), adaptCallbackFunction(fn, argTypes));
401
+ const args = [_toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), adaptCallbackFunction(fn, argTypes, returnType, native)];
402
+ const scalarArgs = argTypes.map(scalarResult);
403
+ if (scalarArgs.some(Boolean)) args.push(scalarArgs);
404
+ return this._lib.callback(...args);
360
405
  }
361
406
 
362
407
  /**
@@ -403,8 +448,8 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
403
448
  * WinDLL - come CDLL ma con stdcall di default (per Windows)
404
449
  */
405
450
  class WinDLL extends CDLL {
406
- func(name, returnType, argTypes = [], options = {}) {
407
- return super.func(name, returnType, argTypes, {
451
+ _createFunction(name, returnType, argTypes = [], options = {}) {
452
+ return super._createFunction(name, returnType, argTypes, {
408
453
  abi: "stdcall",
409
454
  ...options,
410
455
  });
@@ -412,33 +457,15 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
412
457
  }
413
458
 
414
459
  /**
415
- * OleDLL - come WinDLL ma auto-lancia errore se restype è HRESULT e il
416
- * valore ritornato è negativo (HRESULT failure code).
460
+ * OleDLL - come WinDLL ma con restype HRESULT un valore negativo (codice di
461
+ * errore HRESULT) lancia un errore.
417
462
  *
418
- * Python ctypes parity: `ctypes.OleDLL`.
463
+ * Python ctypes parity: `ctypes.OleDLL`; come HRESULT._check_retval_ il
464
+ * controllo precede errcheck e non viene sostituito da esso.
419
465
  */
420
466
  class OleDLL extends WinDLL {
421
- func(name, returnType, argTypes = [], options = {}) {
422
- const fn = super.func(name, returnType, argTypes, options);
423
-
424
- // If the return type is tagged as HRESULT, install an errcheck that
425
- // throws on negative values (Python's OleDLL behavior).
426
- if (returnType && returnType._isHResult) {
427
- const prevErrcheck = fn.errcheck;
428
- fn.errcheck = (result, func, args) => {
429
- const r = prevErrcheck ? prevErrcheck(result, func, args) : result;
430
- const n = typeof r === "bigint" ? Number(r) : r;
431
- if (typeof n === "number" && n < 0) {
432
- const hex = (n >>> 0).toString(16).padStart(8, "0").toUpperCase();
433
- const err = new Error(`OleDLL '${name}' failed with HRESULT 0x${hex}`);
434
- err.hresult = n;
435
- err.winerror = n >>> 0;
436
- throw err;
437
- }
438
- return r;
439
- };
440
- }
441
- return fn;
467
+ _defaultRestype() {
468
+ return OleDLL.defaultRestype;
442
469
  }
443
470
  }
444
471
 
@@ -12,17 +12,14 @@
12
12
  *
13
13
  * @example Main-thread callback (fast)
14
14
  * ```javascript
15
- * import { callback, c_int } from 'node-ctypes';
15
+ * import { callback, c_int, POINTER } from 'node-ctypes';
16
16
  *
17
- * // Comparison function for qsort
17
+ * // Comparison function for qsort: POINTER(c_int) arguments are pointers
18
+ * // (c_void_p arguments arrive as addresses, bigint).
18
19
  * const compareInts = callback(
19
- * (a, b) => {
20
- * const aVal = a.readInt32LE(0);
21
- * const bVal = b.readInt32LE(0);
22
- * return aVal - bVal;
23
- * },
20
+ * (a, b) => a[0] - b[0],
24
21
  * c_int, // return type
25
- * [c_void_p, c_void_p] // arg types
22
+ * [POINTER(c_int), POINTER(c_int)] // arg types
26
23
  * );
27
24
  *
28
25
  * // Use callback.pointer to pass to C
@@ -57,7 +54,7 @@
57
54
  */
58
55
 
59
56
  import { _toNativeReturnType, _toNativeTypes } from "./types.js";
60
- import { adaptCallbackFunction } from "./conversions.js";
57
+ import { adaptCallbackFunction, scalarResult } from "./conversions.js";
61
58
  import { trackCallback } from "./callback-tracker.js";
62
59
 
63
60
  /**
@@ -99,19 +96,15 @@ import { trackCallback } from "./callback-tracker.js";
99
96
  *
100
97
  * @example Basic callback usage
101
98
  * ```javascript
102
- * import { CDLL, callback, c_int, c_char_p } from 'node-ctypes';
99
+ * import { CDLL, callback, c_int, POINTER } from 'node-ctypes';
103
100
  *
104
101
  * const libc = new CDLL(null);
105
102
  *
106
103
  * // Create callback for qsort comparison
107
104
  * const compare = callback(
108
- * (aPtr, bPtr) => {
109
- * const a = aPtr.readInt32LE(0);
110
- * const b = bPtr.readInt32LE(0);
111
- * return a - b;
112
- * },
105
+ * (aPtr, bPtr) => aPtr.contents.value - bPtr.contents.value,
113
106
  * c_int,
114
- * [c_void_p, c_void_p]
107
+ * [POINTER(c_int), POINTER(c_int)]
115
108
  * );
116
109
  *
117
110
  * // Sort array of integers
@@ -153,8 +146,10 @@ import { trackCallback } from "./callback-tracker.js";
153
146
  * @see {@link threadSafeCallback} for thread-safe callbacks
154
147
  */
155
148
  export function callback(fn, returnType, argTypes = [], native, abi = undefined) {
156
- const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
157
- if (abi) args.push(abi);
149
+ const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
150
+ const scalarArgs = argTypes.map(scalarResult);
151
+ if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
152
+ else if (abi) args.push(abi);
158
153
  const cb = new native.Callback(...args);
159
154
 
160
155
  const wrapper = {
@@ -282,8 +277,10 @@ export function callback(fn, returnType, argTypes = [], native, abi = undefined)
282
277
  * @see {@link callback} for main-thread-only callbacks
283
278
  */
284
279
  export function threadSafeCallback(fn, returnType, argTypes = [], native, abi = undefined) {
285
- const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
286
- if (abi) args.push(abi);
280
+ const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
281
+ const scalarArgs = argTypes.map(scalarResult);
282
+ if (scalarArgs.some(Boolean)) args.push(abi ?? "default", scalarArgs);
283
+ else if (abi) args.push(abi);
287
284
  const cb = new native.ThreadSafeCallback(...args);
288
285
 
289
286
  const wrapper = {