node-ctypes 1.14.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.
@@ -38,7 +38,8 @@
38
38
  * ```
39
39
  */
40
40
 
41
- import { _toNativeType, _toNativeTypes } from "./types.js";
41
+ import { _toNativeReturnType, _toNativeTypes } from "./types.js";
42
+ import { argumentConverters, convertArguments, resultConverter } from "./conversions.js";
42
43
  import { callback as createCallback } from "./callback.js";
43
44
 
44
45
  /**
@@ -165,6 +166,21 @@ function applyParamflags(rawFn, restype, argtypes, paramflags) {
165
166
  };
166
167
  }
167
168
 
169
+ /**
170
+ * Normalize a paramflags entry: Python tuple `[flag, name, default]`
171
+ * (flag 1 = in, 2 = out, 4 = in defaulting to 0) or `{ dir, name, default }`.
172
+ * @private
173
+ */
174
+ function toParamFlag(pf) {
175
+ if (!Array.isArray(pf)) return pf;
176
+ const [flag = 1, name, ...rest] = pf;
177
+ const dir = flag & 2 ? "out" : "in";
178
+ const result = { dir, name };
179
+ if (rest.length > 0) result.default = rest[0];
180
+ else if (flag & 4) result.default = 0;
181
+ return result;
182
+ }
183
+
168
184
  /**
169
185
  * Attach a `.bind(library, name, paramflags)` method to a CFUNCTYPE/WINFUNCTYPE
170
186
  * factory, enabling Python-style typed binding with in/out params.
@@ -177,6 +193,7 @@ function attachBind(factory, restype, argtypes, abi) {
177
193
  if (!Array.isArray(paramflags)) {
178
194
  throw new TypeError("paramflags must be an array");
179
195
  }
196
+ paramflags = paramflags.map(toParamFlag);
180
197
  if (paramflags.length !== argtypes.length) {
181
198
  throw new TypeError(`paramflags length (${paramflags.length}) must match argtypes length (${argtypes.length})`);
182
199
  }
@@ -192,33 +209,51 @@ function attachBind(factory, restype, argtypes, abi) {
192
209
  return factory;
193
210
  }
194
211
 
195
- /**
196
- * Creates a function pointer type factory with cdecl calling convention.
197
- *
198
- * @param {Function|Object|number} restype - Return type
199
- * @param {...(Function|Object|number)} argtypes - Argument types
200
- * @returns {Function} Factory that accepts a BigInt address and returns a callable
201
- */
202
- export function createCFUNCTYPE(native) {
203
- return function CFUNCTYPE(restype, ...argtypes) {
204
- const nativeRestype = _toNativeType(restype, native);
212
+ // Tipo funzione CFUNCTYPE / WINFUNCTYPE: chiamato con un indirizzo restituisce
213
+ // una funzione chiamabile, con una funzione JS crea un callback C.
214
+ function createFuncPtrType(native, typeName, abi) {
215
+ return function (restype, ...argtypes) {
216
+ const nativeRestype = _toNativeReturnType(restype, native);
205
217
  const nativeArgtypes = _toNativeTypes(argtypes, native);
218
+ const converters = argumentConverters(argtypes, native);
219
+ const convertResult = resultConverter(restype);
206
220
 
207
- function factory(addressOrFn) {
221
+ function factory(addressOrFn, paramflags) {
208
222
  // Python ctypes parity: CFUNCTYPE(...)(jsFunc) wraps a JS function as a C callback.
209
223
  if (typeof addressOrFn === "function") {
210
- return createCallback(addressOrFn, restype, argtypes, native);
224
+ return createCallback(addressOrFn, restype, argtypes, native, abi);
225
+ }
226
+ // Python: prototype((name, dll)) / prototype((name, dll), paramflags)
227
+ // binds an exported function of a library to this prototype.
228
+ if (Array.isArray(addressOrFn)) {
229
+ const [name, library] = addressOrFn;
230
+ if (typeof name !== "string" || library === null || typeof library !== "object" || typeof library.symbol !== "function") {
231
+ throw new TypeError(`${typeName}: expected [name, library]`);
232
+ }
233
+ if (paramflags !== undefined) {
234
+ return factory.bind(library, name, paramflags);
235
+ }
236
+ addressOrFn = library.symbol(name);
211
237
  }
212
- const address = addressOrFn;
238
+ // Python accetta l'indirizzo come int: anche qui number o BigInt.
239
+ const address = typeof addressOrFn === "number" ? BigInt(addressOrFn) : addressOrFn;
213
240
  if (typeof address !== "bigint") {
214
- throw new TypeError("CFUNCTYPE: argument must be a BigInt address or a JS function");
241
+ throw new TypeError(`${typeName}: argument must be an address (BigInt or number), a JS function or [name, library]`);
215
242
  }
216
243
 
217
- const ffiFunc = new native.FFIFunction(address, null, nativeRestype, nativeArgtypes);
244
+ const ffiFunc = abi ? new native.FFIFunction(address, null, nativeRestype, nativeArgtypes, { abi }) : new native.FFIFunction(address, null, nativeRestype, nativeArgtypes);
245
+
246
+ // Come le funzioni di CDLL: restype POINTER/CFUNCTYPE convertito, ed
247
+ // errcheck applicato sul valore convertito.
248
+ let jsErrcheck = null;
249
+ const finish = (result, args) => {
250
+ if (convertResult === undefined) return result;
251
+ const converted = convertResult(result);
252
+ return jsErrcheck === null ? converted : jsErrcheck(converted, callMethod, args);
253
+ };
218
254
 
219
255
  const callMethod = function (...args) {
220
- const processedArgs = processArgs(args);
221
- return ffiFunc.call(...processedArgs);
256
+ return finish(ffiFunc.call(...convertArguments(args, converters)), args);
222
257
  };
223
258
 
224
259
  Object.defineProperties(callMethod, {
@@ -227,8 +262,7 @@ export function createCFUNCTYPE(native) {
227
262
  _ffi: { value: ffiFunc },
228
263
  callAsync: {
229
264
  value: function (...args) {
230
- const processedArgs = processArgs(args);
231
- return ffiFunc.callAsync(...processedArgs);
265
+ return ffiFunc.callAsync(...convertArguments(args, converters)).then((result) => finish(result, args));
232
266
  },
233
267
  writable: false,
234
268
  enumerable: false,
@@ -236,11 +270,15 @@ export function createCFUNCTYPE(native) {
236
270
  },
237
271
  errcheck: {
238
272
  get() {
239
- return ffiFunc._errcheck;
273
+ return ffiFunc._errcheck ?? null;
240
274
  },
241
275
  set(callback) {
242
276
  ffiFunc._errcheck = callback;
243
- ffiFunc.setErrcheck(callback);
277
+ if (convertResult !== undefined) {
278
+ jsErrcheck = callback ?? null;
279
+ } else {
280
+ ffiFunc.setErrcheck(callback);
281
+ }
244
282
  },
245
283
  enumerable: false,
246
284
  configurable: true,
@@ -254,109 +292,30 @@ export function createCFUNCTYPE(native) {
254
292
  factory.restype = restype;
255
293
  factory.argtypes = argtypes;
256
294
  factory._isFuncPtr = true;
257
- attachBind(factory, restype, argtypes, undefined);
295
+ attachBind(factory, restype, argtypes, abi);
258
296
 
259
297
  return factory;
260
298
  };
261
299
  }
262
300
 
263
301
  /**
264
- * Creates a function pointer type factory with stdcall calling convention.
302
+ * Creates a function pointer type factory with cdecl calling convention.
265
303
  *
266
- * @param {Function|Object|number} restype - Return type
267
- * @param {...(Function|Object|number)} argtypes - Argument types
268
- * @returns {Function} Factory that accepts a BigInt address and returns a callable
304
+ * @param {Object} native - Native module reference
305
+ * @returns {Function} `CFUNCTYPE(restype, ...argtypes)`: factory that accepts an
306
+ * address (BigInt or number) and returns a callable, or a JS function and
307
+ * returns a callback
269
308
  */
270
- export function createWINFUNCTYPE(native) {
271
- return function WINFUNCTYPE(restype, ...argtypes) {
272
- const nativeRestype = _toNativeType(restype, native);
273
- const nativeArgtypes = _toNativeTypes(argtypes, native);
274
-
275
- function factory(addressOrFn) {
276
- // Python ctypes parity: WINFUNCTYPE(...)(jsFunc) wraps a JS function as a stdcall callback.
277
- if (typeof addressOrFn === "function") {
278
- return createCallback(addressOrFn, restype, argtypes, native, "stdcall");
279
- }
280
- const address = addressOrFn;
281
- if (typeof address !== "bigint") {
282
- throw new TypeError("WINFUNCTYPE: argument must be a BigInt address or a JS function");
283
- }
284
-
285
- const ffiFunc = new native.FFIFunction(address, null, nativeRestype, nativeArgtypes, { abi: "stdcall" });
286
-
287
- const callMethod = function (...args) {
288
- const processedArgs = processArgs(args);
289
- return ffiFunc.call(...processedArgs);
290
- };
291
-
292
- Object.defineProperties(callMethod, {
293
- funcName: { value: `0x${address.toString(16)}` },
294
- address: { value: ffiFunc.address },
295
- _ffi: { value: ffiFunc },
296
- callAsync: {
297
- value: function (...args) {
298
- const processedArgs = processArgs(args);
299
- return ffiFunc.callAsync(...processedArgs);
300
- },
301
- writable: false,
302
- enumerable: false,
303
- configurable: false,
304
- },
305
- errcheck: {
306
- get() {
307
- return ffiFunc._errcheck;
308
- },
309
- set(callback) {
310
- ffiFunc._errcheck = callback;
311
- ffiFunc.setErrcheck(callback);
312
- },
313
- enumerable: false,
314
- configurable: true,
315
- },
316
- });
317
-
318
- return callMethod;
319
- }
320
-
321
- // Attach metadata + paramflags binding to the factory (stdcall)
322
- factory.restype = restype;
323
- factory.argtypes = argtypes;
324
- factory._isFuncPtr = true;
325
- attachBind(factory, restype, argtypes, "stdcall");
326
-
327
- return factory;
328
- };
309
+ export function createCFUNCTYPE(native) {
310
+ return createFuncPtrType(native, "CFUNCTYPE", undefined);
329
311
  }
330
312
 
331
313
  /**
332
- * Process arguments, extracting _buffer from struct/union proxies.
333
- * @private
314
+ * Creates a function pointer type factory with stdcall calling convention.
315
+ *
316
+ * @param {Object} native - Native module reference
317
+ * @returns {Function} `WINFUNCTYPE(restype, ...argtypes)`, as {@link createCFUNCTYPE}
334
318
  */
335
- function processArgs(args) {
336
- // Scansione iniziale: se nessun argomento è un Structure/Union proxy
337
- // (i.e. nessuno ha un `_buffer` Buffer esposto), ritorna l'array
338
- // originale senza copiare — evita un'allocazione per ogni call.
339
- const len = args.length;
340
- let firstToExtract = -1;
341
- for (let i = 0; i < len; i++) {
342
- const arg = args[i];
343
- if (arg && typeof arg === "object" && arg._buffer !== undefined && Buffer.isBuffer(arg._buffer)) {
344
- firstToExtract = i;
345
- break;
346
- }
347
- }
348
- if (firstToExtract === -1) return args;
349
-
350
- // Fallback: serve materializzare un nuovo array solo dal primo match.
351
- const out = new Array(len);
352
- for (let i = 0; i < firstToExtract; i++) out[i] = args[i];
353
- for (let i = firstToExtract; i < len; i++) {
354
- const arg = args[i];
355
- if (arg && typeof arg === "object" && arg._buffer !== undefined && Buffer.isBuffer(arg._buffer)) {
356
- out[i] = arg._buffer;
357
- } else {
358
- out[i] = arg;
359
- }
360
- }
361
- return out;
319
+ export function createWINFUNCTYPE(native) {
320
+ return createFuncPtrType(native, "WINFUNCTYPE", "stdcall");
362
321
  }
@@ -11,13 +11,13 @@
11
11
  * ctypes.cdll.msvcrt.printf(b"Hi\n")
12
12
  * ```
13
13
  *
14
- * Here the library requires `argtypes` + `restype` to be set before calling
15
- * (no silent `c_int` default — you'll get "restype not set" otherwise):
14
+ * As in Python, `restype` defaults to `c_int` and, without `argtypes`, the
15
+ * arguments are converted from their JS values:
16
16
  *
17
17
  * ```javascript
18
18
  * import { cdll, windll, c_int, c_char_p } from "node-ctypes";
19
19
  *
20
- * // Attribute-style (Python parity, requires explicit types):
20
+ * // Attribute-style (Python parity):
21
21
  * cdll.msvcrt.printf.argtypes = [c_char_p];
22
22
  * cdll.msvcrt.printf.restype = c_int;
23
23
  * cdll.msvcrt.printf("Hi\n");
@@ -39,11 +39,14 @@
39
39
  */
40
40
  export function createLazyLoader(DllClass) {
41
41
  const cache = new Map();
42
+ // Python: cdll.LoadLibrary(name, ...) crea sempre una nuova istanza.
43
+ const LoadLibrary = (name, ...args) => new DllClass(name, ...args);
42
44
  return new Proxy(Object.create(null), {
43
45
  get(_, libName) {
44
46
  if (typeof libName !== "string") return undefined;
45
47
  // Skip symbol/private probes used by Node's inspect / util.inspect.
46
48
  if (libName === "then") return undefined;
49
+ if (libName === "LoadLibrary") return LoadLibrary;
47
50
  if (!cache.has(libName)) {
48
51
  cache.set(libName, new DllClass(libName));
49
52
  }
package/lib/core/types.js CHANGED
@@ -162,6 +162,11 @@ export function _toNativeType(type, native) {
162
162
  return native.CType.POINTER;
163
163
  }
164
164
 
165
+ // 2b. Tipo funzione CFUNCTYPE / WINFUNCTYPE (Python: argtypes = [..., CMPFUNC])
166
+ if (typeof type === "function" && type._isFuncPtr === true) {
167
+ return native.CType.POINTER;
168
+ }
169
+
165
170
  // 3. Structure / Union subclass → native StructType.
166
171
  if (typeof type === "function" && typeof type._buildStruct === "function") {
167
172
  const def = type._structDef || type._buildStruct();
@@ -178,7 +183,7 @@ export function _toNativeType(type, native) {
178
183
  }
179
184
 
180
185
  // 5. Array wrapper
181
- if (type && typeof type === "object" && type._isArrayType) {
186
+ if (type && (typeof type === "object" || typeof type === "function") && type._isArrayType) {
182
187
  return type._native || type;
183
188
  }
184
189
 
@@ -189,6 +194,15 @@ export function _toNativeType(type, native) {
189
194
  return type;
190
195
  }
191
196
 
197
+ /**
198
+ * Come _toNativeType, per i tipi di ritorno: `null` vale `void`
199
+ * (Python ctypes: `restype = None`, `CFUNCTYPE(None, ...)`).
200
+ */
201
+ export function _toNativeReturnType(type, native) {
202
+ if (type === null) return native.CType.VOID;
203
+ return _toNativeType(type, native);
204
+ }
205
+
192
206
  /**
193
207
  * Normalizza un array di tipi (batch). Non-array → pass-through.
194
208
  */