node-ctypes 2.4.0 → 2.6.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.
- package/CHANGELOG.md +117 -1
- package/README.md +94 -8
- package/build/Release/ctypes-darwin-arm64.node +0 -0
- package/build/Release/ctypes-darwin-x64.node +0 -0
- package/build/Release/ctypes-linux-arm64-musl.node +0 -0
- package/build/Release/ctypes-linux-arm64.node +0 -0
- package/build/Release/ctypes-linux-x64-musl.node +0 -0
- package/build/Release/ctypes-linux-x64.node +0 -0
- package/build/Release/ctypes-win32-arm64.node +0 -0
- package/build/Release/ctypes-win32-x64.node +0 -0
- package/lib/core/Library.js +39 -83
- package/lib/core/callback.js +54 -7
- package/lib/core/conversions.js +159 -26
- package/lib/core/funcptr.js +91 -27
- package/lib/index.d.ts +82 -13
- package/lib/memory/buffer.js +23 -5
- package/lib/memory/pointer.js +42 -36
- package/lib/structures/Structure.js +52 -6
- package/lib/structures/helpers/common.js +18 -13
- package/lib/structures/helpers/struct.js +42 -26
- package/lib/structures/helpers/union.js +4 -4
- package/lib/types/primitives.js +3 -2
- package/package.json +1 -1
package/lib/core/conversions.js
CHANGED
|
@@ -10,9 +10,9 @@ import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
|
|
|
10
10
|
import { ArgumentError } from "../platform/errors.js";
|
|
11
11
|
import { encodeWide } from "../memory/buffer.js";
|
|
12
12
|
import { buildWrapper } from "../structures/helpers/wrap.js";
|
|
13
|
-
import { byrefOwners, isScalarSubclass, resolveParameter, scalarView } from "../structures/helpers/common.js";
|
|
13
|
+
import { activeArgumentOwners as argumentOwnerRegistry, byrefOwners, isScalarSubclass, resolveParameter, scalarView, structArgumentFactories } from "../structures/helpers/common.js";
|
|
14
14
|
|
|
15
|
-
const activeArgumentOwners =
|
|
15
|
+
const activeArgumentOwners = argumentOwnerRegistry;
|
|
16
16
|
|
|
17
17
|
function retainArgument(owners, value) {
|
|
18
18
|
if (owners !== undefined && value !== null && (typeof value === "object" || typeof value === "function")) owners.push(value);
|
|
@@ -31,6 +31,68 @@ export function argumentsNeedOwners(args) {
|
|
|
31
31
|
return false;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
// The general fallback receives the hook snapshot taken before any owner probe.
|
|
35
|
+
export function specializeCall(ffiFunc, method, converters, state, invoke, captureHere = true) {
|
|
36
|
+
const [C0, C1, C2, C3, C4, C5] = converters;
|
|
37
|
+
const hasAdapters = converters.some((convert) => convert.requiresOwners);
|
|
38
|
+
switch (converters.length) {
|
|
39
|
+
case 0:
|
|
40
|
+
return function () {
|
|
41
|
+
const checked = captureHere ? state.errcheck : null;
|
|
42
|
+
if (checked !== null || arguments.length !== 0) return invoke(arguments, checked);
|
|
43
|
+
return ffiFunc[method]();
|
|
44
|
+
};
|
|
45
|
+
case 1:
|
|
46
|
+
return function (a0) {
|
|
47
|
+
const checked = captureHere ? state.errcheck : null;
|
|
48
|
+
if (checked !== null || arguments.length !== 1) return invoke(arguments, checked);
|
|
49
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
50
|
+
return ffiFunc[method](C0(a0));
|
|
51
|
+
};
|
|
52
|
+
case 2:
|
|
53
|
+
return function (a0, a1) {
|
|
54
|
+
const checked = captureHere ? state.errcheck : null;
|
|
55
|
+
if (checked !== null || arguments.length !== 2) return invoke(arguments, checked);
|
|
56
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
57
|
+
return ffiFunc[method](C0(a0), C1(a1));
|
|
58
|
+
};
|
|
59
|
+
case 3:
|
|
60
|
+
return function (a0, a1, a2) {
|
|
61
|
+
const checked = captureHere ? state.errcheck : null;
|
|
62
|
+
if (checked !== null || arguments.length !== 3) return invoke(arguments, checked);
|
|
63
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
64
|
+
return ffiFunc[method](C0(a0), C1(a1), C2(a2));
|
|
65
|
+
};
|
|
66
|
+
case 4:
|
|
67
|
+
return function (a0, a1, a2, a3) {
|
|
68
|
+
const checked = captureHere ? state.errcheck : null;
|
|
69
|
+
if (checked !== null || arguments.length !== 4) return invoke(arguments, checked);
|
|
70
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
71
|
+
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3));
|
|
72
|
+
};
|
|
73
|
+
case 5:
|
|
74
|
+
return function (a0, a1, a2, a3, a4) {
|
|
75
|
+
const checked = captureHere ? state.errcheck : null;
|
|
76
|
+
if (checked !== null || arguments.length !== 5) return invoke(arguments, checked);
|
|
77
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3) || needsArgumentOwners(a4))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
78
|
+
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4));
|
|
79
|
+
};
|
|
80
|
+
case 6:
|
|
81
|
+
return function (a0, a1, a2, a3, a4, a5) {
|
|
82
|
+
const checked = captureHere ? state.errcheck : null;
|
|
83
|
+
if (checked !== null || arguments.length !== 6) return invoke(arguments, checked);
|
|
84
|
+
if (captureHere && (hasAdapters || needsArgumentOwners(a0) || needsArgumentOwners(a1) || needsArgumentOwners(a2) || needsArgumentOwners(a3) || needsArgumentOwners(a4) || needsArgumentOwners(a5)))
|
|
85
|
+
return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
86
|
+
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5));
|
|
87
|
+
};
|
|
88
|
+
default:
|
|
89
|
+
return function (...args) {
|
|
90
|
+
const checked = captureHere ? state.errcheck : null;
|
|
91
|
+
return invoke(args, checked);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
34
96
|
// The registry is a GC root, including while another converter reenters JS.
|
|
35
97
|
export function callWithArgumentOwners(ffiFunc, method, args, converters, finish, resultHandler, checkedCall) {
|
|
36
98
|
const owners = [];
|
|
@@ -111,12 +173,13 @@ const isStructType = (t) => t !== null && (typeof t === "function" || typeof t =
|
|
|
111
173
|
|
|
112
174
|
/**
|
|
113
175
|
* Converter for a struct/union passed by value. A plain object (fields by
|
|
114
|
-
* name, a node-ctypes extension)
|
|
115
|
-
*
|
|
116
|
-
*
|
|
176
|
+
* name, a node-ctypes extension) uses the type's field writers. Simple
|
|
177
|
+
* functional structs omit the transient Proxy; other types still construct
|
|
178
|
+
* an instance so custom constructors and complex layouts keep their behavior.
|
|
179
|
+
* An array is rejected, as a Python tuple.
|
|
117
180
|
*/
|
|
118
181
|
function structArgument(T, index) {
|
|
119
|
-
const instance = typeof T === "function" ? (values) => new T(values) : (values) => T.create(values);
|
|
182
|
+
const instance = typeof T === "function" ? (values) => new T(values) : (structArgumentFactories.get(T) ?? ((values) => T.create(values)));
|
|
120
183
|
const coerce = mirrorsActive ? coerceStructValue : coerceObject;
|
|
121
184
|
return (a, owners) => {
|
|
122
185
|
a = resolveArgument(a, owners, index);
|
|
@@ -167,28 +230,84 @@ export function coerceVariadic(a, owners) {
|
|
|
167
230
|
* @returns {Function[]} One converter per declared argument
|
|
168
231
|
*/
|
|
169
232
|
export function argumentConverters(argTypes, native) {
|
|
170
|
-
const pointerKinds = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
|
|
171
233
|
const baseConverter = (t, index) => {
|
|
172
234
|
if (isStructType(t)) return structArgument(t, index);
|
|
173
235
|
if (t !== null && (typeof t === "function" || typeof t === "object") && t._isArrayType === true) return arrayArgument(t, index);
|
|
174
236
|
if (t !== null && typeof t === "object" && t._pointerTo !== undefined) return pointerArgument(t, index, native);
|
|
237
|
+
const kind = typeof t === "function" ? t._type : t;
|
|
238
|
+
if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
|
|
239
|
+
if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
|
|
175
240
|
if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
|
|
176
|
-
|
|
177
|
-
return (a, owners) => {
|
|
178
|
-
a = resolveArgument(a, owners, index);
|
|
179
|
-
if (a === null || typeof a !== "object") return a;
|
|
180
|
-
retainArgument(owners, a);
|
|
181
|
-
if (a._isSimpleCDataInstance === true && a instanceof t) return a.value;
|
|
182
|
-
return coerceObject(a, owners);
|
|
183
|
-
};
|
|
241
|
+
return scalarArgument(t, index);
|
|
184
242
|
};
|
|
185
243
|
return argTypes.map((t, index) => {
|
|
186
244
|
const base = baseConverter(t, index);
|
|
187
|
-
if (t === null || (typeof t !== "function" && typeof t !== "object")
|
|
188
|
-
|
|
245
|
+
if (t === null || (typeof t !== "function" && typeof t !== "object")) return base;
|
|
246
|
+
const fromParam = t.from_param;
|
|
247
|
+
if (fromParam === undefined) return base;
|
|
248
|
+
return fromParamArgument(t, base.fromParam ?? base, index, fromParam);
|
|
189
249
|
});
|
|
190
250
|
}
|
|
191
251
|
|
|
252
|
+
function pointerValue(value, native) {
|
|
253
|
+
const buffer = value._buffer;
|
|
254
|
+
if (mirrorsActive) refresh(buffer);
|
|
255
|
+
return native.POINTER_SIZE === 8 ? buffer.readBigUInt64LE(0) : BigInt(buffer.readUInt32LE(0));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function voidPointerArgument(index, native) {
|
|
259
|
+
return (value, owners) => {
|
|
260
|
+
value = resolveArgument(value, owners, index);
|
|
261
|
+
if (typeof value === "number" && !Number.isInteger(value)) {
|
|
262
|
+
throw new ArgumentError(`argument ${index + 1}: TypeError: 'float' object cannot be interpreted as ctypes.c_void_p`);
|
|
263
|
+
}
|
|
264
|
+
if (value?._isSimpleCDataInstance === true && value.constructor._isPointerValued === true) {
|
|
265
|
+
retainArgument(owners, value);
|
|
266
|
+
return pointerValue(value, native);
|
|
267
|
+
}
|
|
268
|
+
return objectMemory(value, owners);
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function stringArgument(T, kind, index, native) {
|
|
273
|
+
const wide = kind === native.CType.WSTRING;
|
|
274
|
+
const charKind = wide ? "wchar" : "char";
|
|
275
|
+
const typeName = wide ? "c_wchar_p" : "c_char_p";
|
|
276
|
+
const fail = (value) => {
|
|
277
|
+
const name =
|
|
278
|
+
typeof value === "bigint" || (typeof value === "number" && Number.isInteger(value)) ? "int" : typeof value === "number" ? "float" : typeof value === "boolean" ? "bool" : value?.constructor?.name === "Object" ? "object" : typeof value;
|
|
279
|
+
throw new ArgumentError(`argument ${index + 1}: TypeError: '${name}' object cannot be interpreted as ctypes.${typeName}`);
|
|
280
|
+
};
|
|
281
|
+
const convert = (value, owners) => {
|
|
282
|
+
value = resolveArgument(value, owners, index);
|
|
283
|
+
if (value === null || value === undefined || typeof value === "string") return value;
|
|
284
|
+
retainArgument(owners, value);
|
|
285
|
+
if (value?._isSimpleCDataInstance === true) {
|
|
286
|
+
if (typeof T === "function" ? !(value instanceof T) : value.constructor._type !== kind) fail(value);
|
|
287
|
+
return pointerValue(value, native);
|
|
288
|
+
}
|
|
289
|
+
const element = value?._pointerType?._pointerTo ?? value?._arrayType?.elementType;
|
|
290
|
+
if (element !== undefined) {
|
|
291
|
+
if (element._charKind !== charKind) fail(value);
|
|
292
|
+
return objectMemory(value, owners);
|
|
293
|
+
}
|
|
294
|
+
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return objectMemory(value, owners);
|
|
295
|
+
fail(value);
|
|
296
|
+
};
|
|
297
|
+
// A custom from_param result is already adapted and may be a c_void_p.
|
|
298
|
+
Object.defineProperty(convert, "fromParam", {
|
|
299
|
+
value: (value, owners) => {
|
|
300
|
+
value = resolveArgument(value, owners, index);
|
|
301
|
+
if (value?._isSimpleCDataInstance === true) {
|
|
302
|
+
retainArgument(owners, value);
|
|
303
|
+
return value.constructor._isPointerValued === true ? pointerValue(value, native) : value.value;
|
|
304
|
+
}
|
|
305
|
+
return objectMemory(value, owners);
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
return convert;
|
|
309
|
+
}
|
|
310
|
+
|
|
192
311
|
function scalarArgument(T, index) {
|
|
193
312
|
const boolean = T._isBoolean === true;
|
|
194
313
|
return (value, owners) => {
|
|
@@ -221,7 +340,11 @@ function pointerArgument(T, index, native) {
|
|
|
221
340
|
throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible pointer, expected POINTER(${base.name ?? "type"})`);
|
|
222
341
|
};
|
|
223
342
|
const convert = (value, owners) => {
|
|
343
|
+
const argument = value;
|
|
224
344
|
value = resolveArgument(value, owners, index);
|
|
345
|
+
const direct = value === argument;
|
|
346
|
+
// CPython's implicit byref, array decay and NULL conversions apply only to the original argument.
|
|
347
|
+
if (!direct && value === null) fail();
|
|
225
348
|
if (value === null || value === undefined || typeof value === "bigint") return value;
|
|
226
349
|
if (typeof value === "number") {
|
|
227
350
|
if (!Number.isInteger(value)) fail();
|
|
@@ -233,7 +356,10 @@ function pointerArgument(T, index, native) {
|
|
|
233
356
|
retainArgument(owners, buffer);
|
|
234
357
|
return buffer;
|
|
235
358
|
}
|
|
236
|
-
if (typeof base === "function" && value instanceof base)
|
|
359
|
+
if (typeof base === "function" && value instanceof base) {
|
|
360
|
+
if (!direct) fail();
|
|
361
|
+
return objectMemory(value, owners);
|
|
362
|
+
}
|
|
237
363
|
const reference = value !== null && (typeof value === "object" || typeof value === "function") ? byrefOwners.get(value) : undefined;
|
|
238
364
|
if (reference !== undefined) {
|
|
239
365
|
if (reference.type !== undefined && !compatibleType(reference.type, base)) fail();
|
|
@@ -244,6 +370,7 @@ function pointerArgument(T, index, native) {
|
|
|
244
370
|
return objectMemory(value, owners);
|
|
245
371
|
}
|
|
246
372
|
if (value?._arrayType !== undefined) {
|
|
373
|
+
if (!direct) fail();
|
|
247
374
|
if ((!compatibleType(value._arrayType, base) && !compatibleType(value._arrayType.elementType, base)) || value._arrayType._swapped_) fail();
|
|
248
375
|
return coerceObject(value, owners);
|
|
249
376
|
}
|
|
@@ -269,14 +396,13 @@ function pointerArgument(T, index, native) {
|
|
|
269
396
|
* `_as_parameter_`) is converted as the declared type. Its errors become
|
|
270
397
|
* ArgumentError "argument N: <name>: <message>", as in Python.
|
|
271
398
|
*/
|
|
272
|
-
function fromParamArgument(T, base, index) {
|
|
399
|
+
function fromParamArgument(T, base, index, fromParam) {
|
|
273
400
|
const converter = (a, owners) => {
|
|
274
401
|
retainArgument(owners, a);
|
|
275
402
|
let converted;
|
|
276
403
|
try {
|
|
277
|
-
converted =
|
|
404
|
+
converted = Reflect.apply(fromParam, T, [a]);
|
|
278
405
|
} catch (e) {
|
|
279
|
-
if (e instanceof ArgumentError) throw e;
|
|
280
406
|
throw new ArgumentError(`argument ${index + 1}: ${e?.name ?? "Error"}: ${e?.message ?? String(e)}`, { cause: e });
|
|
281
407
|
}
|
|
282
408
|
retainArgument(owners, converted);
|
|
@@ -379,10 +505,10 @@ export function scalarResult(restype) {
|
|
|
379
505
|
|
|
380
506
|
export function resultCheck(restype, name, loader = "FFI") {
|
|
381
507
|
const check = restype?._check_retval_;
|
|
382
|
-
if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
|
|
383
508
|
const hresult = restype?._isHResult === true;
|
|
384
509
|
if (!hresult && check === undefined) return undefined;
|
|
385
510
|
return (result) => {
|
|
511
|
+
if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
|
|
386
512
|
if (hresult) {
|
|
387
513
|
const value = result?._isSimpleCDataInstance === true ? result.value : result;
|
|
388
514
|
const number = typeof value === "bigint" ? Number(value) : value;
|
|
@@ -432,6 +558,16 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
432
558
|
const hasVariants = variantArgs.some(Boolean);
|
|
433
559
|
const variantResult = returnType?._isVariantBool === true;
|
|
434
560
|
const toResult = stringResult(returnType, native);
|
|
561
|
+
const convertResult = (result) => {
|
|
562
|
+
if (variantResult) return returnType.from_param(result);
|
|
563
|
+
if (toResult !== undefined && typeof result === "string") return toResult(result);
|
|
564
|
+
return result !== null && (typeof result === "object" || typeof result === "function") ? coerceValue(result) : result;
|
|
565
|
+
};
|
|
566
|
+
if (!hasScalars && !hasVariants && !hasPointers && !hasStructs) {
|
|
567
|
+
return function (...args) {
|
|
568
|
+
return convertResult(fn.apply(this, args));
|
|
569
|
+
};
|
|
570
|
+
}
|
|
435
571
|
return function (...args) {
|
|
436
572
|
if (hasScalars) {
|
|
437
573
|
for (let i = 0; i < scalarTypes.length; i++) {
|
|
@@ -456,10 +592,7 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
456
592
|
if (structViews[i] !== null) args[i] = structViews[i](args[i]);
|
|
457
593
|
}
|
|
458
594
|
}
|
|
459
|
-
|
|
460
|
-
if (variantResult) return returnType.from_param(result);
|
|
461
|
-
if (toResult !== undefined && typeof result === "string") return toResult(result);
|
|
462
|
-
return result !== null && (typeof result === "object" || typeof result === "function") ? coerceValue(result) : result;
|
|
595
|
+
return convertResult(fn.apply(this, args));
|
|
463
596
|
};
|
|
464
597
|
}
|
|
465
598
|
|
package/lib/core/funcptr.js
CHANGED
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
39
|
import { _toNativeReturnType, _toNativeTypes } from "./types.js";
|
|
40
|
-
import { argumentConverters, argumentsNeedOwners, callWithArgumentOwners, callWithResultHandler, convertArguments, resultCheck, resultConverter, scalarResult, structResult } from "./conversions.js";
|
|
40
|
+
import { argumentConverters, argumentsNeedOwners, callWithArgumentOwners, callWithResultHandler, convertArguments, resultCheck, resultConverter, scalarResult, specializeCall, structResult } from "./conversions.js";
|
|
41
41
|
import { callback as createCallback } from "./callback.js";
|
|
42
|
-
import { isScalarSubclass, scalarOutparam } from "../structures/helpers/common.js";
|
|
42
|
+
import { isScalarSubclass, keepFunctionOwner, scalarOutparam } from "../structures/helpers/common.js";
|
|
43
43
|
import { cacheWeakValue, createTypeKey } from "../utils/cache.js";
|
|
44
44
|
|
|
45
45
|
const prototypeOwners = new WeakMap();
|
|
@@ -218,7 +218,7 @@ function toParamFlag(pf) {
|
|
|
218
218
|
* factory, enabling Python-style typed binding with in/out params.
|
|
219
219
|
* @private
|
|
220
220
|
*/
|
|
221
|
-
function attachBind(factory, restype, argtypes, abi) {
|
|
221
|
+
function attachBind(factory, restype, argtypes, abi, signature) {
|
|
222
222
|
factory.bind = function bindWithFlags(library, symbolName, paramflags) {
|
|
223
223
|
// Validate paramflags up-front so shape errors surface before the symbol
|
|
224
224
|
// lookup (which may fail for unrelated reasons like missing export).
|
|
@@ -235,7 +235,7 @@ function attachBind(factory, restype, argtypes, abi) {
|
|
|
235
235
|
throw new TypeError(`paramflags[${i}] is "out" but argtype ${i} is not a POINTER(T)`);
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
|
-
const rawFn = library._createFunction(symbolName, restype, argtypes, abi ? { abi } : {});
|
|
238
|
+
const rawFn = library._createFunction(symbolName, restype, argtypes, abi ? { abi } : {}, signature);
|
|
239
239
|
const bound = applyParamflags(rawFn, restype, argtypes, paramflags);
|
|
240
240
|
prototypeOwners.set(bound, factory);
|
|
241
241
|
return bound;
|
|
@@ -266,19 +266,22 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
266
266
|
}
|
|
267
267
|
const nativeRestype = _toNativeReturnType(restype, native);
|
|
268
268
|
const nativeArgtypes = _toNativeTypes(argtypes, native);
|
|
269
|
+
const converters = argumentConverters(argtypes, native);
|
|
270
|
+
const hasAdapters = converters.some((convert) => convert.requiresOwners);
|
|
271
|
+
const represent = resultConverter(restype);
|
|
272
|
+
const check = resultCheck(restype, typeName);
|
|
273
|
+
const convertResult = check === undefined ? represent : represent === undefined ? check : (value) => check(represent(value));
|
|
274
|
+
const signature = { nativeRestype, nativeArgtypes, converters, represent, check };
|
|
269
275
|
|
|
270
276
|
function factory(addressOrFn, paramflags) {
|
|
277
|
+
let callback;
|
|
278
|
+
let released = false;
|
|
279
|
+
let activeCalls = 0;
|
|
271
280
|
// Python ctypes parity: CFUNCTYPE(...)(jsFunc) wraps a JS function as a C callback.
|
|
272
281
|
if (typeof addressOrFn === "function") {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
return callback;
|
|
282
|
+
callback = createCallback(addressOrFn, restype, argtypes, native, abi);
|
|
283
|
+
addressOrFn = callback.pointer;
|
|
276
284
|
}
|
|
277
|
-
const converters = argumentConverters(argtypes, native);
|
|
278
|
-
const hasAdapters = converters.some((convert) => convert.requiresOwners);
|
|
279
|
-
const represent = resultConverter(restype);
|
|
280
|
-
const check = resultCheck(restype, typeName);
|
|
281
|
-
const convertResult = check === undefined ? represent : represent === undefined ? check : (value) => check(represent(value));
|
|
282
285
|
// Python: prototype((name, dll)) / prototype((name, dll), paramflags)
|
|
283
286
|
// binds an exported function of a library to this prototype.
|
|
284
287
|
let ownerLibrary;
|
|
@@ -306,54 +309,115 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
306
309
|
if (ownerLibrary) options.library = ownerLibrary;
|
|
307
310
|
if (structResult(restype)) options.struct_buffer = true;
|
|
308
311
|
if (scalarResult(restype)) options.scalar_buffer = true;
|
|
309
|
-
|
|
312
|
+
let ffiFunc;
|
|
313
|
+
try {
|
|
314
|
+
ffiFunc = new native.FFIFunction(address, null, nativeRestype, nativeArgtypes, options);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
callback?.release();
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
310
319
|
|
|
311
320
|
// Come le funzioni di CDLL: restype POINTER/CFUNCTYPE convertito, ed
|
|
312
321
|
// errcheck applicato sul valore convertito.
|
|
313
|
-
|
|
322
|
+
const callState = { errcheck: null };
|
|
314
323
|
let checkedSync;
|
|
315
324
|
const finish = (result) => (convertResult === undefined ? result : convertResult(result));
|
|
316
325
|
const checkedCall = (method, args, checked) => {
|
|
317
|
-
const
|
|
326
|
+
const originalArgs = Array.isArray(args) ? args : Array.prototype.slice.call(args);
|
|
327
|
+
const resultHandler = (result) => checked(finish(result), callMethod, originalArgs);
|
|
318
328
|
const call = method === "call" ? (checkedSync ??= ffiFunc._makeCheckedCall()) : undefined;
|
|
319
|
-
return callWithResultHandler(ffiFunc, method,
|
|
329
|
+
return callWithResultHandler(ffiFunc, method, originalArgs, converters, resultHandler, hasAdapters || argumentsNeedOwners(originalArgs), call);
|
|
320
330
|
};
|
|
321
331
|
|
|
322
|
-
const
|
|
323
|
-
if (
|
|
332
|
+
const invoke = (args, checked) => {
|
|
333
|
+
if (checked !== null) return checkedCall("call", args, checked);
|
|
324
334
|
if (hasAdapters || argumentsNeedOwners(args)) return callWithArgumentOwners(ffiFunc, "call", args, converters, finish);
|
|
325
335
|
return finish(ffiFunc.call(...convertArguments(args, converters)), args);
|
|
326
336
|
};
|
|
337
|
+
let callMethod =
|
|
338
|
+
convertResult === undefined && !hasAdapters && converters.length <= 6
|
|
339
|
+
? specializeCall(ffiFunc, "call", converters, callState, invoke)
|
|
340
|
+
: function (...args) {
|
|
341
|
+
return invoke(args, callState.errcheck);
|
|
342
|
+
};
|
|
327
343
|
|
|
344
|
+
const asyncCall = function (...args) {
|
|
345
|
+
if (callState.errcheck !== null) return checkedCall("callAsync", args, callState.errcheck);
|
|
346
|
+
if (hasAdapters || argumentsNeedOwners(args)) return callWithArgumentOwners(ffiFunc, "callAsync", args, converters, finish);
|
|
347
|
+
return ffiFunc.callAsync(...convertArguments(args, converters)).then((result) => finish(result, args));
|
|
348
|
+
};
|
|
349
|
+
let callAsync = asyncCall;
|
|
350
|
+
let callbackProperties = {};
|
|
351
|
+
if (callback !== undefined) {
|
|
352
|
+
const assertLive = () => {
|
|
353
|
+
if (released) throw new Error("Callback has been released");
|
|
354
|
+
};
|
|
355
|
+
const release = () => {
|
|
356
|
+
if (activeCalls !== 0) throw new Error("Cannot release callback while calls to it are in progress");
|
|
357
|
+
if (!released) {
|
|
358
|
+
callback.release();
|
|
359
|
+
released = true;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const call = callMethod;
|
|
363
|
+
callMethod = function (...args) {
|
|
364
|
+
assertLive();
|
|
365
|
+
activeCalls++;
|
|
366
|
+
try {
|
|
367
|
+
return call(...args);
|
|
368
|
+
} finally {
|
|
369
|
+
activeCalls--;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
callAsync = function (...args) {
|
|
373
|
+
assertLive();
|
|
374
|
+
activeCalls++;
|
|
375
|
+
try {
|
|
376
|
+
return asyncCall(...args).finally(() => activeCalls--);
|
|
377
|
+
} catch (error) {
|
|
378
|
+
activeCalls--;
|
|
379
|
+
throw error;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
callbackProperties = Object.getOwnPropertyDescriptors(callback);
|
|
383
|
+
callbackProperties.release.value = release;
|
|
384
|
+
callbackProperties[Symbol.dispose].value = release;
|
|
385
|
+
callbackProperties._as_parameter_ = {
|
|
386
|
+
get() {
|
|
387
|
+
assertLive();
|
|
388
|
+
return callback.pointer;
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|
|
328
392
|
Object.defineProperties(callMethod, {
|
|
393
|
+
...callbackProperties,
|
|
394
|
+
name: { value: "callMethod", configurable: true },
|
|
395
|
+
length: { value: 0, configurable: true },
|
|
329
396
|
funcName: { value: `0x${address.toString(16)}` },
|
|
330
397
|
address: { value: ffiFunc.address },
|
|
331
|
-
_as_parameter_: { value: ffiFunc.address },
|
|
398
|
+
_as_parameter_: callbackProperties._as_parameter_ ?? { value: ffiFunc.address },
|
|
332
399
|
_ffi: { value: ffiFunc },
|
|
333
400
|
callAsync: {
|
|
334
|
-
value:
|
|
335
|
-
if (jsErrcheck !== null) return checkedCall("callAsync", args, jsErrcheck);
|
|
336
|
-
if (hasAdapters || argumentsNeedOwners(args)) return callWithArgumentOwners(ffiFunc, "callAsync", args, converters, finish);
|
|
337
|
-
return ffiFunc.callAsync(...convertArguments(args, converters)).then((result) => finish(result, args));
|
|
338
|
-
},
|
|
401
|
+
value: callAsync,
|
|
339
402
|
writable: false,
|
|
340
403
|
enumerable: false,
|
|
341
404
|
configurable: false,
|
|
342
405
|
},
|
|
343
406
|
errcheck: {
|
|
344
407
|
get() {
|
|
345
|
-
return
|
|
408
|
+
return callState.errcheck;
|
|
346
409
|
},
|
|
347
410
|
set(callback) {
|
|
348
411
|
callback = callback ?? null;
|
|
349
412
|
if (callback !== null && typeof callback !== "function") throw new TypeError("errcheck must be a function or null");
|
|
350
|
-
|
|
413
|
+
callState.errcheck = callback;
|
|
351
414
|
},
|
|
352
415
|
enumerable: false,
|
|
353
416
|
configurable: true,
|
|
354
417
|
},
|
|
355
418
|
});
|
|
356
419
|
|
|
420
|
+
if (callback !== undefined) keepFunctionOwner(callMethod, callback);
|
|
357
421
|
prototypeOwners.set(callMethod, factory);
|
|
358
422
|
return callMethod;
|
|
359
423
|
}
|
|
@@ -362,7 +426,7 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
362
426
|
factory.restype = restype;
|
|
363
427
|
factory.argtypes = argtypes.slice();
|
|
364
428
|
factory._isFuncPtr = true;
|
|
365
|
-
attachBind(factory, restype, argtypes, abi);
|
|
429
|
+
attachBind(factory, restype, argtypes, abi, signature);
|
|
366
430
|
|
|
367
431
|
signatures.set(factory, { restype, argtypes });
|
|
368
432
|
cacheWeakValue(cache, key, factory);
|
package/lib/index.d.ts
CHANGED
|
@@ -134,7 +134,7 @@ export type FFIType = AnyType | StructureClass | PointerTypeDef | ArrayTypeDef |
|
|
|
134
134
|
* @example
|
|
135
135
|
* ```javascript
|
|
136
136
|
* import { Version } from 'node-ctypes';
|
|
137
|
-
* console.log(Version.toString()); // "2.
|
|
137
|
+
* console.log(Version.toString()); // "2.5.0"
|
|
138
138
|
* ```
|
|
139
139
|
*
|
|
140
140
|
* @category Library Loading
|
|
@@ -464,6 +464,10 @@ export interface FunctionWrapper {
|
|
|
464
464
|
/** Call the function. */
|
|
465
465
|
(...args: any[]): any;
|
|
466
466
|
|
|
467
|
+
/** Resolve the native function address. */
|
|
468
|
+
readonly address: bigint;
|
|
469
|
+
readonly _as_parameter_: bigint;
|
|
470
|
+
|
|
467
471
|
/** Call the function asynchronously on a worker thread. */
|
|
468
472
|
callAsync(...args: any[]): Promise<any>;
|
|
469
473
|
|
|
@@ -636,8 +640,57 @@ export interface ThreadSafeCallbackWrapper extends CallbackWrapper {
|
|
|
636
640
|
* callback exists. Calls from other threads are delivered while it runs.
|
|
637
641
|
*/
|
|
638
642
|
unref(): this;
|
|
643
|
+
/**
|
|
644
|
+
* Transfer a nonzero opaque error pointer to nativeContext.onError on the
|
|
645
|
+
* original caller thread, after resume. Only during this callback; once per
|
|
646
|
+
* invocation. The callback must also return its ABI's error sentinel.
|
|
647
|
+
* Ownership transfers to onError, which must consume the pointer.
|
|
648
|
+
*/
|
|
649
|
+
setNativeError(error: bigint): void;
|
|
650
|
+
/** Execute a snapshot of queued calls on the owning Node thread; return the number claimed. */
|
|
651
|
+
drain(): number;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* A raw function address, ctypes callable or low-level native function handle.
|
|
656
|
+
* JavaScript-backed callbacks are not valid hooks. Object targets are retained
|
|
657
|
+
* by the native dispatcher until release and queued delivery cleanup.
|
|
658
|
+
* @category Callbacks
|
|
659
|
+
*/
|
|
660
|
+
export type NativeCallbackHook = bigint | (({ readonly _as_parameter_: bigint } | { readonly address: bigint }) & { readonly _callback?: never });
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Opt-in native runtime hooks. Addresses are resolved once at construction.
|
|
664
|
+
* Keep the callback and hook libraries alive until every invocation returns;
|
|
665
|
+
* retaining a function does not prevent explicit close()/release().
|
|
666
|
+
* Hooks use the default C ABI directly, bypassing JS argument conversion and
|
|
667
|
+
* errcheck. They must not throw or execute JavaScript and do not provide
|
|
668
|
+
* subinterpreter support.
|
|
669
|
+
* @category Callbacks
|
|
670
|
+
*/
|
|
671
|
+
export interface NativeCallbackContext {
|
|
672
|
+
/** `void *suspend(void)`: detach caller state before a foreign thread waits. */
|
|
673
|
+
suspend: NativeCallbackHook;
|
|
674
|
+
/** `void resume(void *)`: restore that state on the same thread, even on dispatch failure. */
|
|
675
|
+
resume: NativeCallbackHook;
|
|
676
|
+
/** `void onError(void *)`: consume setNativeError's pointer on the original thread. */
|
|
677
|
+
onError: NativeCallbackHook;
|
|
678
|
+
/** `void notify(void)`: after queueing on a foreign thread, while suspended; may wake the host, never run JS. */
|
|
679
|
+
notify?: NativeCallbackHook;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** @category Callbacks */
|
|
683
|
+
export interface ThreadSafeCallbackOptions {
|
|
684
|
+
abi?: FunctionOptions["abi"];
|
|
685
|
+
nativeContext?: NativeCallbackContext;
|
|
639
686
|
}
|
|
640
687
|
|
|
688
|
+
/**
|
|
689
|
+
* A CFUNCTYPE/WINFUNCTYPE callback that is also a typed native caller.
|
|
690
|
+
* @category Callbacks
|
|
691
|
+
*/
|
|
692
|
+
export type CallableCallback<TArgs extends readonly FFIType[], TRet extends FFIType | null> = TypedFFIFunction<TArgs, TRet> & CallbackWrapper;
|
|
693
|
+
|
|
641
694
|
/**
|
|
642
695
|
* Native callback class for main-thread callbacks.
|
|
643
696
|
* @category Callbacks
|
|
@@ -671,6 +724,10 @@ export class ThreadSafeCallback extends Callback {
|
|
|
671
724
|
ref(): this;
|
|
672
725
|
/** Do not keep the Node.js event loop alive. */
|
|
673
726
|
unref(): this;
|
|
727
|
+
/** See {@link ThreadSafeCallbackWrapper.setNativeError}. */
|
|
728
|
+
setNativeError(error: bigint): void;
|
|
729
|
+
/** See {@link ThreadSafeCallbackWrapper.drain}. */
|
|
730
|
+
drain(): number;
|
|
674
731
|
}
|
|
675
732
|
|
|
676
733
|
// =============================================================================
|
|
@@ -1197,8 +1254,10 @@ export interface PointerInstance<T = any> {
|
|
|
1197
1254
|
* @category Pointers
|
|
1198
1255
|
*/
|
|
1199
1256
|
export interface PointerTypeDef<T = any> {
|
|
1200
|
-
/** The type
|
|
1201
|
-
readonly _pointerTo:
|
|
1257
|
+
/** The resolved base type, including for lazy pointer declarations. */
|
|
1258
|
+
readonly _pointerTo: T;
|
|
1259
|
+
/** Python ctypes alias for the resolved base type. */
|
|
1260
|
+
readonly _type_: T;
|
|
1202
1261
|
/** Size of the pointed-to type. */
|
|
1203
1262
|
readonly _baseSize: number;
|
|
1204
1263
|
/** Pointer size (always 8 on 64-bit). */
|
|
@@ -1585,7 +1644,12 @@ export function callback<TRet extends CallbackRestype, const TArgs extends reado
|
|
|
1585
1644
|
*
|
|
1586
1645
|
* @category Callbacks
|
|
1587
1646
|
*/
|
|
1588
|
-
export function threadSafeCallback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(
|
|
1647
|
+
export function threadSafeCallback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(
|
|
1648
|
+
fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>,
|
|
1649
|
+
returnType: TRet,
|
|
1650
|
+
argTypes?: TArgs,
|
|
1651
|
+
options?: FunctionOptions["abi"] | ThreadSafeCallbackOptions,
|
|
1652
|
+
): ThreadSafeCallbackWrapper;
|
|
1589
1653
|
|
|
1590
1654
|
/**
|
|
1591
1655
|
* Create a function pointer type with cdecl calling convention.
|
|
@@ -1640,12 +1704,12 @@ export interface FuncPtrFactory<TRet extends FFIType | null = FFIType | null, TA
|
|
|
1640
1704
|
(address: bigint | number): TypedFFIFunction<TArgs, TRet>;
|
|
1641
1705
|
new (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
|
|
1642
1706
|
/**
|
|
1643
|
-
* Call with a JS function to produce a
|
|
1644
|
-
* as argument or struct field
|
|
1707
|
+
* Call with a JS function to produce a directly callable, typed C callback,
|
|
1708
|
+
* usable as an argument or struct field. Keep it referenced while C may
|
|
1645
1709
|
* call it; `release()` frees it.
|
|
1646
1710
|
*/
|
|
1647
|
-
(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>):
|
|
1648
|
-
new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>):
|
|
1711
|
+
(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
|
|
1712
|
+
new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
|
|
1649
1713
|
/**
|
|
1650
1714
|
* Bind an exported function of a library, optionally with paramflags.
|
|
1651
1715
|
* Python: `prototype((name, dll))` / `prototype((name, dll), paramflags)`.
|
|
@@ -2011,9 +2075,10 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, o
|
|
|
2011
2075
|
* When the target is a {@link PointerTypeDef}, returns a {@link PointerInstance} with
|
|
2012
2076
|
* `.contents` and `[index]` access — equivalent to Python's
|
|
2013
2077
|
* `cast(c_void_p(addr), POINTER(MyStruct))`.
|
|
2078
|
+
* A {@link FuncPtrFactory} target returns a caller with that prototype.
|
|
2014
2079
|
*
|
|
2015
|
-
* @param ptr -
|
|
2016
|
-
* @param targetType - The target type (primitive, struct, or
|
|
2080
|
+
* @param ptr - Memory, a pointer/address, or a native function/callback
|
|
2081
|
+
* @param targetType - The target type (primitive, struct, POINTER or CFUNCTYPE)
|
|
2017
2082
|
*
|
|
2018
2083
|
* @example Cast to POINTER for typed array access
|
|
2019
2084
|
* ```javascript
|
|
@@ -2031,8 +2096,11 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, o
|
|
|
2031
2096
|
*
|
|
2032
2097
|
* @category Pointers
|
|
2033
2098
|
*/
|
|
2034
|
-
|
|
2035
|
-
export function cast(ptr:
|
|
2099
|
+
type CastSource = MemorySource | ArrayBuffer | ByRefAddress | FFIFunction | CallbackWrapper | null;
|
|
2100
|
+
export function cast<T>(ptr: CastSource, targetType: PointerTypeDef<T>): PointerInstance<T>;
|
|
2101
|
+
export function cast<TRet extends FFIType | null, TArgs extends readonly FFIType[]>(ptr: CastSource, targetType: FuncPtrFactory<TRet, TArgs>): TypedFFIFunction<TArgs, TRet>;
|
|
2102
|
+
export function cast<T extends SimpleCDataConstructor<"pointer"> | SimpleCDataConstructor<"string"> | SimpleCDataConstructor<"wstring">>(ptr: CastSource, targetType: T): InstanceType<T>;
|
|
2103
|
+
export function cast(ptr: CastSource, targetType: AnyType | StructDef | StructureClass): any;
|
|
2036
2104
|
|
|
2037
2105
|
/**
|
|
2038
2106
|
* Create a pointer type for a given base type.
|
|
@@ -2091,6 +2159,7 @@ export function POINTER<T extends AnyType | StructureClass>(baseType: () => T):
|
|
|
2091
2159
|
*
|
|
2092
2160
|
* @category Pointers
|
|
2093
2161
|
*/
|
|
2162
|
+
export function pointer<T>(obj: PointerInstance<T>): PointerInstance<PointerTypeDef<T>>;
|
|
2094
2163
|
export function pointer<T extends Structure<any>>(obj: T): PointerInstance<new (...args: any[]) => T>;
|
|
2095
2164
|
export function pointer<V>(obj: SimpleCDataInstance<V>): PointerInstance;
|
|
2096
2165
|
export function pointer(obj: Buffer | { _buffer: Buffer }): PointerInstance;
|
|
@@ -2238,7 +2307,7 @@ export type JsFromTag<Tag extends string> = Tag extends "void"
|
|
|
2238
2307
|
: Tag extends "wstring"
|
|
2239
2308
|
? string | null
|
|
2240
2309
|
: Tag extends "pointer"
|
|
2241
|
-
? bigint |
|
|
2310
|
+
? bigint | null
|
|
2242
2311
|
: any;
|
|
2243
2312
|
|
|
2244
2313
|
/**
|