node-ctypes 1.13.0 → 2.0.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.
@@ -39,6 +39,9 @@
39
39
  * ```
40
40
  */
41
41
 
42
+ import { _toNativeReturnType } from "./types.js";
43
+ import { adaptCallbackFunction, argumentConverters, convertArguments, coerceValue, resultConverter } from "./conversions.js";
44
+
42
45
  /**
43
46
  * Creates the Library-related classes with required dependencies injected.
44
47
  *
@@ -51,65 +54,71 @@
51
54
  * @private
52
55
  */
53
56
  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);
67
+ }
68
+ return id;
69
+ };
70
+
54
71
  class FunctionWrapper {
55
72
  constructor(cdll, name) {
56
73
  const argtypes = [];
57
74
  let restype = undefined;
58
75
  let cachedFunc = null;
59
76
 
60
- // Create a function and proxy it to make it callable
61
- const func = (...args) => {
62
- if (restype === undefined) {
63
- throw new Error(`Function ${name}: restype not set`);
64
- }
77
+ // Python ctypes: restype predefinito c_int.
78
+ const resolve = () => {
65
79
  if (!cachedFunc) {
66
- cachedFunc = cdll.func(name, restype, argtypes);
80
+ cachedFunc = cdll.func(name, restype === undefined ? FunctionWrapper.defaultRestype : restype, argtypes);
67
81
  }
68
- return cachedFunc(...args);
82
+ return cachedFunc;
69
83
  };
70
84
 
71
- // Proxy the function to intercept property access
72
- return new Proxy(func, {
73
- get(target, prop) {
74
- if (prop === "argtypes") return argtypes;
75
- if (prop === "restype") return restype;
76
- if (prop === "errcheck") return cachedFunc ? cachedFunc.errcheck : undefined;
77
- if (prop === "callAsync") {
78
- if (restype === undefined) {
79
- throw new Error(`Function ${name}: restype not set`);
80
- }
81
- if (!cachedFunc) {
82
- cachedFunc = cdll.func(name, restype, argtypes);
83
- }
84
- return cachedFunc.callAsync;
85
- }
86
- return target[prop];
87
- },
88
- set(target, prop, value) {
89
- if (prop === "argtypes") {
85
+ // Funzione semplice con accessor invece di un Proxy: ogni chiamata
86
+ // attraverso un Proxy costava ~20 ns in più.
87
+ const func = (...args) => (cachedFunc ?? resolve())(...args);
88
+
89
+ Object.defineProperties(func, {
90
+ argtypes: {
91
+ get: () => argtypes,
92
+ set: (value) => {
90
93
  argtypes.splice(0, argtypes.length, ...value);
91
94
  cachedFunc = null; // Invalidate cache
92
- return true;
93
- }
94
- if (prop === "restype") {
95
+ },
96
+ configurable: true,
97
+ },
98
+ restype: {
99
+ get: () => (restype === undefined ? FunctionWrapper.defaultRestype : restype),
100
+ set: (value) => {
95
101
  restype = value;
96
102
  cachedFunc = null; // Invalidate cache
97
- return true;
98
- }
99
- if (prop === "errcheck") {
100
- if (!cachedFunc) {
101
- if (restype === undefined) {
102
- throw new Error(`Function ${name}: restype not set`);
103
- }
104
- cachedFunc = cdll.func(name, restype, argtypes);
105
- }
106
- cachedFunc.errcheck = value;
107
- return true;
108
- }
109
- target[prop] = value;
110
- return true;
103
+ },
104
+ configurable: true,
105
+ },
106
+ errcheck: {
107
+ get: () => (cachedFunc ? cachedFunc.errcheck : null),
108
+ set: (value) => {
109
+ resolve().errcheck = value;
110
+ },
111
+ configurable: true,
112
+ },
113
+ callAsync: {
114
+ get: () => resolve().callAsync,
115
+ // Come con il Proxy precedente: l'assegnazione non ha effetto.
116
+ set: () => {},
117
+ configurable: true,
111
118
  },
112
119
  });
120
+
121
+ return func;
113
122
  }
114
123
  }
115
124
 
@@ -118,7 +127,11 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
118
127
  */
119
128
  class CDLL {
120
129
  constructor(libPath, options = {}) {
121
- this._lib = new Library(libPath);
130
+ // Python ctypes: CDLL(name, mode) con il mode di dlopen in posizione.
131
+ if (typeof options === "number") {
132
+ options = { mode: options };
133
+ }
134
+ this._lib = options.mode === undefined ? new Library(libPath) : new Library(libPath, options.mode);
122
135
  // Use LRU cache to prevent unbounded memory growth
123
136
  const cacheSize = options.cacheSize ?? 1000;
124
137
  this._cache = new LRUCache(cacheSize);
@@ -159,7 +172,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
159
172
  * @returns {Function} Funzione callable
160
173
  */
161
174
  func(name, returnType, argTypes = [], options = {}) {
162
- const cacheKey = `${name}:${returnType}:${argTypes.join(",")}`;
175
+ const cacheKey = `${name}:${typeKey(returnType)}:${argTypes.map(typeKey).join(",")}`;
163
176
 
164
177
  if (this._cache.has(cacheKey)) {
165
178
  return this._cache.get(cacheKey);
@@ -171,7 +184,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
171
184
  ...(this._use_last_error ? { use_last_error: true } : {}),
172
185
  ...(this._use_errno ? { use_errno: true } : {}),
173
186
  };
174
- const ffiFunc = this._lib.func(name, _toNativeType(returnType, native), _toNativeTypes(argTypes, native), mergedOptions);
187
+ const ffiFunc = this._lib.func(name, _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), mergedOptions);
175
188
 
176
189
  // =========================================================================
177
190
  // OPTIMIZATION: Create specialized wrapper based on argument types
@@ -204,178 +217,81 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
204
217
  return arg;
205
218
  };
206
219
 
207
- let callMethod;
208
-
209
- // COERCE: unified inline coercion for any arg type.
210
- // - primitives (number, string, bigint, null, undefined): pass through
211
- // - object with ._buffer: unwrap to the raw Buffer (struct/array wrapper)
212
- // - object with ._as_parameter_: unwrap (ctypes object protocol)
213
- // - anything else (plain Buffer, etc.): pass through as-is
214
- // Replaces both the old UNWRAP (primitive fast path) and the slow-path
215
- // processedArgs loop, covering pointer/string/wstring args without allocation.
216
- const COERCE = (a) => {
217
- if (a === null || typeof a !== "object") return a;
218
- if (a._buffer !== undefined) return a._buffer;
219
- if (a._as_parameter_ !== undefined) return a._as_parameter_;
220
- return a;
221
- };
222
-
223
- if (argCount === 0) {
224
- // FAST PATH: No declared arguments — still support variadic
225
- callMethod = function (...args) {
226
- if (args.length === 0) {
227
- return ffiFunc.call();
228
- }
229
- return ffiFunc.call(...args);
230
- };
231
- } else if (!anyFromParam) {
232
- // FAST PATH: No from_param — arity-specialized wrappers with inline COERCE.
233
- // Covers all arg types (primitive, pointer, string, struct wrapper) without
234
- // allocating a rest-params array or a processedArgs accumulator.
235
- // Each case checks arguments.length to forward variadic extras (cold path).
220
+ // Conversione degli argomenti come il from_param di base di Python
221
+ // (vedi conversions.js): un convertitore per posizione dichiarata.
222
+ const C = argumentConverters(argTypes, native);
223
+ const [C0, C1, C2, C3, C4, C5] = C;
224
+ const convertAll = (args) => convertArguments(args, C);
225
+
226
+ // Funzioni specializzate per numero di argomenti (niente array per la
227
+ // chiamata comune); `method` è "call" o "callAsync".
228
+ 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
+ }
236
239
  switch (argCount) {
240
+ case 0:
241
+ return function () {
242
+ return arguments.length === 0 ? ffiFunc[method]() : ffiFunc[method](...convertAll(arguments));
243
+ };
237
244
  case 1:
238
- callMethod = function (a0) {
239
- if (arguments.length === 1) return ffiFunc.call(COERCE(a0));
240
- const n = arguments.length,
241
- arr = new Array(n);
242
- arr[0] = COERCE(a0);
243
- for (let i = 1; i < n; i++) arr[i] = arguments[i];
244
- return ffiFunc.call(...arr);
245
+ return function (a0) {
246
+ return arguments.length === 1 ? ffiFunc[method](C0(a0)) : ffiFunc[method](...convertAll(arguments));
245
247
  };
246
- break;
247
248
  case 2:
248
- callMethod = function (a0, a1) {
249
- if (arguments.length === 2) return ffiFunc.call(COERCE(a0), COERCE(a1));
250
- const n = arguments.length,
251
- arr = new Array(n);
252
- arr[0] = COERCE(a0);
253
- arr[1] = COERCE(a1);
254
- for (let i = 2; i < n; i++) arr[i] = arguments[i];
255
- return ffiFunc.call(...arr);
249
+ return function (a0, a1) {
250
+ return arguments.length === 2 ? ffiFunc[method](C0(a0), C1(a1)) : ffiFunc[method](...convertAll(arguments));
256
251
  };
257
- break;
258
252
  case 3:
259
- callMethod = function (a0, a1, a2) {
260
- if (arguments.length === 3) return ffiFunc.call(COERCE(a0), COERCE(a1), COERCE(a2));
261
- const n = arguments.length,
262
- arr = new Array(n);
263
- arr[0] = COERCE(a0);
264
- arr[1] = COERCE(a1);
265
- arr[2] = COERCE(a2);
266
- for (let i = 3; i < n; i++) arr[i] = arguments[i];
267
- return ffiFunc.call(...arr);
253
+ return function (a0, a1, a2) {
254
+ return arguments.length === 3 ? ffiFunc[method](C0(a0), C1(a1), C2(a2)) : ffiFunc[method](...convertAll(arguments));
268
255
  };
269
- break;
270
256
  case 4:
271
- callMethod = function (a0, a1, a2, a3) {
272
- if (arguments.length === 4) return ffiFunc.call(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3));
273
- const n = arguments.length,
274
- arr = new Array(n);
275
- arr[0] = COERCE(a0);
276
- arr[1] = COERCE(a1);
277
- arr[2] = COERCE(a2);
278
- arr[3] = COERCE(a3);
279
- for (let i = 4; i < n; i++) arr[i] = arguments[i];
280
- return ffiFunc.call(...arr);
257
+ 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));
281
259
  };
282
- break;
283
260
  case 5:
284
- callMethod = function (a0, a1, a2, a3, a4) {
285
- if (arguments.length === 5) return ffiFunc.call(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3), COERCE(a4));
286
- const n = arguments.length,
287
- arr = new Array(n);
288
- arr[0] = COERCE(a0);
289
- arr[1] = COERCE(a1);
290
- arr[2] = COERCE(a2);
291
- arr[3] = COERCE(a3);
292
- arr[4] = COERCE(a4);
293
- for (let i = 5; i < n; i++) arr[i] = arguments[i];
294
- return ffiFunc.call(...arr);
261
+ 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));
295
263
  };
296
- break;
297
264
  case 6:
298
- callMethod = function (a0, a1, a2, a3, a4, a5) {
299
- if (arguments.length === 6) return ffiFunc.call(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3), COERCE(a4), COERCE(a5));
300
- const n = arguments.length,
301
- arr = new Array(n);
302
- arr[0] = COERCE(a0);
303
- arr[1] = COERCE(a1);
304
- arr[2] = COERCE(a2);
305
- arr[3] = COERCE(a3);
306
- arr[4] = COERCE(a4);
307
- arr[5] = COERCE(a5);
308
- for (let i = 6; i < n; i++) arr[i] = arguments[i];
309
- return ffiFunc.call(...arr);
265
+ 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));
310
267
  };
311
- break;
312
268
  default:
313
- // > 6 args: rest params unavoidable, but still no processedArgs allocation
314
- callMethod = function (...args) {
315
- for (let i = 0; i < args.length; i++) args[i] = COERCE(args[i]);
316
- return ffiFunc.call(...args);
269
+ return function (...args) {
270
+ return ffiFunc[method](...convertAll(args));
317
271
  };
318
272
  }
319
- } else {
320
- // SLOW PATH: anyFromParam = true — must call from_param on each arg.
321
- callMethod = function (...args) {
322
- const processedArgs = new Array(args.length);
323
- for (let i = 0; i < args.length; i++) {
324
- processedArgs[i] = applyParamProtocols(COERCE(args[i]), i);
325
- }
326
- return ffiFunc.call(...processedArgs);
327
- };
328
- }
329
-
330
- // =========================================================================
331
- // ASYNC WRAPPER: same argument processing, but calls callAsync
332
- // Returns a Promise instead of the result directly
333
- // =========================================================================
334
-
335
- let asyncCallMethod;
273
+ };
336
274
 
337
- if (argCount === 0) {
338
- asyncCallMethod = function (...args) {
339
- if (args.length === 0) {
340
- return ffiFunc.callAsync();
341
- }
342
- return ffiFunc.callAsync(...args);
275
+ let callMethod = specialize("call");
276
+ let asyncCallMethod = specialize("callAsync");
277
+
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;
283
+ if (convertResult !== undefined) {
284
+ const rawCall = callMethod;
285
+ const rawAsync = asyncCallMethod;
286
+ const finish = (result, args) => {
287
+ const converted = convertResult(result);
288
+ return jsErrcheck === null ? converted : jsErrcheck(converted, callMethod, args);
289
+ };
290
+ callMethod = function (...args) {
291
+ return finish(rawCall.apply(this, args), args);
343
292
  };
344
- } else if (!anyFromParam) {
345
- // FAST PATH: inline COERCE, no processedArgs allocation
346
- switch (argCount) {
347
- case 1:
348
- asyncCallMethod = (a0) => ffiFunc.callAsync(COERCE(a0));
349
- break;
350
- case 2:
351
- asyncCallMethod = (a0, a1) => ffiFunc.callAsync(COERCE(a0), COERCE(a1));
352
- break;
353
- case 3:
354
- asyncCallMethod = (a0, a1, a2) => ffiFunc.callAsync(COERCE(a0), COERCE(a1), COERCE(a2));
355
- break;
356
- case 4:
357
- asyncCallMethod = (a0, a1, a2, a3) => ffiFunc.callAsync(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3));
358
- break;
359
- case 5:
360
- asyncCallMethod = (a0, a1, a2, a3, a4) => ffiFunc.callAsync(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3), COERCE(a4));
361
- break;
362
- case 6:
363
- asyncCallMethod = (a0, a1, a2, a3, a4, a5) => ffiFunc.callAsync(COERCE(a0), COERCE(a1), COERCE(a2), COERCE(a3), COERCE(a4), COERCE(a5));
364
- break;
365
- default:
366
- asyncCallMethod = function (...args) {
367
- for (let i = 0; i < args.length; i++) args[i] = COERCE(args[i]);
368
- return ffiFunc.callAsync(...args);
369
- };
370
- }
371
- } else {
372
- // SLOW PATH: anyFromParam = true
373
293
  asyncCallMethod = function (...args) {
374
- const processedArgs = new Array(args.length);
375
- for (let i = 0; i < args.length; i++) {
376
- processedArgs[i] = applyParamProtocols(COERCE(args[i]), i);
377
- }
378
- return ffiFunc.callAsync(...processedArgs);
294
+ return rawAsync.apply(this, args).then((result) => finish(result, args));
379
295
  };
380
296
  }
381
297
 
@@ -404,11 +320,15 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
404
320
  // Esponi errcheck come setter/getter
405
321
  errcheck: {
406
322
  get() {
407
- return ffiFunc._errcheck;
323
+ return ffiFunc._errcheck ?? null;
408
324
  },
409
325
  set(callback) {
410
326
  ffiFunc._errcheck = callback;
411
- ffiFunc.setErrcheck(callback);
327
+ if (convertResult !== undefined) {
328
+ jsErrcheck = callback ?? null;
329
+ } else {
330
+ ffiFunc.setErrcheck(callback);
331
+ }
412
332
  },
413
333
  enumerable: false,
414
334
  configurable: true,
@@ -436,7 +356,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
436
356
  * @returns {Object} Oggetto callback con proprietà pointer e metodi
437
357
  */
438
358
  callback(fn, returnType, argTypes = []) {
439
- return this._lib.callback(_toNativeType(returnType, native), _toNativeTypes(argTypes, native), fn);
359
+ return this._lib.callback(_toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), adaptCallbackFunction(fn, argTypes));
440
360
  }
441
361
 
442
362
  /**
@@ -56,7 +56,8 @@
56
56
  * ```
57
57
  */
58
58
 
59
- import { _toNativeType, _toNativeTypes } from "./types.js";
59
+ import { _toNativeReturnType, _toNativeTypes } from "./types.js";
60
+ import { adaptCallbackFunction } from "./conversions.js";
60
61
  import { trackCallback } from "./callback-tracker.js";
61
62
 
62
63
  /**
@@ -152,7 +153,7 @@ import { trackCallback } from "./callback-tracker.js";
152
153
  * @see {@link threadSafeCallback} for thread-safe callbacks
153
154
  */
154
155
  export function callback(fn, returnType, argTypes = [], native, abi = undefined) {
155
- const args = [fn, _toNativeType(returnType, native), _toNativeTypes(argTypes, native)];
156
+ const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
156
157
  if (abi) args.push(abi);
157
158
  const cb = new native.Callback(...args);
158
159
 
@@ -168,6 +169,13 @@ export function callback(fn, returnType, argTypes = [], native, abi = undefined)
168
169
  },
169
170
  _callback: cb,
170
171
  };
172
+ // Python ctypes parity: il callback si passa direttamente come argomento,
173
+ // es. qsort(arr, n, size, cmp). Non enumerabile per non cambiare Object.keys.
174
+ Object.defineProperty(wrapper, "_as_parameter_", {
175
+ get() {
176
+ return cb.pointer;
177
+ },
178
+ });
171
179
  return trackCallback(wrapper, fn, "callback");
172
180
  }
173
181
 
@@ -268,7 +276,7 @@ export function callback(fn, returnType, argTypes = [], native, abi = undefined)
268
276
  * @see {@link callback} for main-thread-only callbacks
269
277
  */
270
278
  export function threadSafeCallback(fn, returnType, argTypes = [], native, abi = undefined) {
271
- const args = [fn, _toNativeType(returnType, native), _toNativeTypes(argTypes, native)];
279
+ const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
272
280
  if (abi) args.push(abi);
273
281
  const cb = new native.ThreadSafeCallback(...args);
274
282
 
@@ -284,5 +292,12 @@ export function threadSafeCallback(fn, returnType, argTypes = [], native, abi =
284
292
  },
285
293
  _callback: cb,
286
294
  };
295
+ // Python ctypes parity: il callback si passa direttamente come argomento,
296
+ // es. qsort(arr, n, size, cmp). Non enumerabile per non cambiare Object.keys.
297
+ Object.defineProperty(wrapper, "_as_parameter_", {
298
+ get() {
299
+ return cb.pointer;
300
+ },
301
+ });
287
302
  return trackCallback(wrapper, fn, "threadSafeCallback");
288
303
  }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * @file conversions.js
3
+ * @module core/conversions
4
+ * @description Argument and result conversions shared by CDLL functions and
5
+ * CFUNCTYPE callers, following Python ctypes (`from_param` and restype
6
+ * conversion).
7
+ */
8
+
9
+ /**
10
+ * Base conversion of an object argument:
11
+ * - struct/union/array instance or Buffer view → its Buffer (by reference)
12
+ * - pointer created from an address → the address
13
+ * - object with `_as_parameter_` (callbacks, adapters) → that value
14
+ * - anything else unchanged
15
+ */
16
+ export function coerceObject(a) {
17
+ if (a === null || typeof a !== "object") return a;
18
+ const b = a._buffer;
19
+ if (b !== undefined) {
20
+ // Puntatore creato da indirizzo (fromAddress): senza Buffer va passato
21
+ // l'indirizzo, altrimenti al C arriverebbe NULL.
22
+ if (b === null && a._pointerType !== undefined) return a.address;
23
+ return b;
24
+ }
25
+ if (a._as_parameter_ !== undefined) return a._as_parameter_;
26
+ return a;
27
+ }
28
+
29
+ /**
30
+ * Python default conversion (no argtypes, variadic arguments): a SimpleCData
31
+ * instance is passed by value (`abs(c_int(-5))`), other objects as
32
+ * {@link coerceObject}.
33
+ */
34
+ export function coerceValue(a) {
35
+ if (a === null || typeof a !== "object") return a;
36
+ if (a._isSimpleCDataInstance === true) return a.value;
37
+ return coerceObject(a);
38
+ }
39
+
40
+ /**
41
+ * Argument converters for `argtypes`, one per position. A SimpleCData instance
42
+ * passed to a simple-type parameter is its value; to a pointer-like parameter
43
+ * (c_void_p, c_char_p, c_wchar_p) only when it is of that type, otherwise its
44
+ * address is passed.
45
+ *
46
+ * @param {Array} argTypes - Declared argument types
47
+ * @param {Object} native - Native module (for CType)
48
+ * @returns {Function[]} One converter per declared argument
49
+ */
50
+ export function argumentConverters(argTypes, native) {
51
+ const pointerKinds = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
52
+ return argTypes.map((t) => {
53
+ if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
54
+ if (!pointerKinds.has(t._type)) return coerceValue;
55
+ return (a) => {
56
+ if (a === null || typeof a !== "object") return a;
57
+ if (a._isSimpleCDataInstance === true && a instanceof t) return a.value;
58
+ return coerceObject(a);
59
+ };
60
+ });
61
+ }
62
+
63
+ /**
64
+ * Convert all call arguments: declared ones with their converter, the rest
65
+ * (variadic or without argtypes) with the Python default conversion.
66
+ */
67
+ export function convertArguments(args, converters) {
68
+ const n = args.length;
69
+ const declared = converters.length;
70
+ const out = new Array(n);
71
+ for (let i = 0; i < n; i++) {
72
+ out[i] = i < declared ? converters[i](args[i]) : coerceValue(args[i]);
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Python restype conversion done in JS: `POINTER(T)` returns a pointer object
79
+ * (`null` for NULL), a CFUNCTYPE type returns a callable. Undefined when the
80
+ * native result is already final.
81
+ *
82
+ * @param {*} restype - Declared return type
83
+ * @returns {Function|undefined} Converter from the native result
84
+ */
85
+ export function resultConverter(restype) {
86
+ if (restype !== null && typeof restype === "object" && restype._pointerTo !== undefined) {
87
+ return (r) => (r === null || r === 0n ? null : restype.fromAddress(r));
88
+ }
89
+ if (typeof restype === "function" && restype._isFuncPtr === true) {
90
+ return (r) => (r === null || r === 0n ? null : restype(r));
91
+ }
92
+ return undefined;
93
+ }
94
+
95
+ /**
96
+ * Adapt a JS function used as a C callback to Python semantics: arguments
97
+ * declared `POINTER(T)` are passed as pointer objects (`null` for NULL), and an
98
+ * object returned by the function (pointer, SimpleCData instance, ...) is
99
+ * converted like an argument.
100
+ *
101
+ * @param {Function} fn - JS callback
102
+ * @param {Array} argTypes - Declared argument types
103
+ * @returns {Function} Function to register with the native callback
104
+ */
105
+ export function adaptCallbackFunction(fn, argTypes) {
106
+ const pointerTypes = argTypes.map((t) => (t !== null && typeof t === "object" && t._pointerTo !== undefined ? t : null));
107
+ const hasPointers = pointerTypes.some((t) => t !== null);
108
+ return function (...args) {
109
+ if (hasPointers) {
110
+ for (let i = 0; i < pointerTypes.length; i++) {
111
+ const T = pointerTypes[i];
112
+ if (T !== null && args[i] !== null) {
113
+ args[i] = T.fromAddress(args[i]);
114
+ }
115
+ }
116
+ }
117
+ const result = fn.apply(this, args);
118
+ return result !== null && typeof result === "object" ? coerceValue(result) : result;
119
+ };
120
+ }