node-ctypes 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -1
- package/README.md +41 -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/conversions.js +159 -25
- package/lib/core/funcptr.js +91 -27
- package/lib/index.d.ts +25 -12
- 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,12 +396,12 @@ 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
406
|
if (e instanceof ArgumentError) throw e;
|
|
280
407
|
throw new ArgumentError(`argument ${index + 1}: ${e?.name ?? "Error"}: ${e?.message ?? String(e)}`, { cause: e });
|
|
@@ -379,10 +506,10 @@ export function scalarResult(restype) {
|
|
|
379
506
|
|
|
380
507
|
export function resultCheck(restype, name, loader = "FFI") {
|
|
381
508
|
const check = restype?._check_retval_;
|
|
382
|
-
if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
|
|
383
509
|
const hresult = restype?._isHResult === true;
|
|
384
510
|
if (!hresult && check === undefined) return undefined;
|
|
385
511
|
return (result) => {
|
|
512
|
+
if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
|
|
386
513
|
if (hresult) {
|
|
387
514
|
const value = result?._isSimpleCDataInstance === true ? result.value : result;
|
|
388
515
|
const number = typeof value === "bigint" ? Number(value) : value;
|
|
@@ -432,6 +559,16 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
432
559
|
const hasVariants = variantArgs.some(Boolean);
|
|
433
560
|
const variantResult = returnType?._isVariantBool === true;
|
|
434
561
|
const toResult = stringResult(returnType, native);
|
|
562
|
+
const convertResult = (result) => {
|
|
563
|
+
if (variantResult) return returnType.from_param(result);
|
|
564
|
+
if (toResult !== undefined && typeof result === "string") return toResult(result);
|
|
565
|
+
return result !== null && (typeof result === "object" || typeof result === "function") ? coerceValue(result) : result;
|
|
566
|
+
};
|
|
567
|
+
if (!hasScalars && !hasVariants && !hasPointers && !hasStructs) {
|
|
568
|
+
return function (...args) {
|
|
569
|
+
return convertResult(fn.apply(this, args));
|
|
570
|
+
};
|
|
571
|
+
}
|
|
435
572
|
return function (...args) {
|
|
436
573
|
if (hasScalars) {
|
|
437
574
|
for (let i = 0; i < scalarTypes.length; i++) {
|
|
@@ -456,10 +593,7 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
456
593
|
if (structViews[i] !== null) args[i] = structViews[i](args[i]);
|
|
457
594
|
}
|
|
458
595
|
}
|
|
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;
|
|
596
|
+
return convertResult(fn.apply(this, args));
|
|
463
597
|
};
|
|
464
598
|
}
|
|
465
599
|
|
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
|
|
@@ -638,6 +638,12 @@ export interface ThreadSafeCallbackWrapper extends CallbackWrapper {
|
|
|
638
638
|
unref(): this;
|
|
639
639
|
}
|
|
640
640
|
|
|
641
|
+
/**
|
|
642
|
+
* A CFUNCTYPE/WINFUNCTYPE callback that is also a typed native caller.
|
|
643
|
+
* @category Callbacks
|
|
644
|
+
*/
|
|
645
|
+
export type CallableCallback<TArgs extends readonly FFIType[], TRet extends FFIType | null> = TypedFFIFunction<TArgs, TRet> & CallbackWrapper;
|
|
646
|
+
|
|
641
647
|
/**
|
|
642
648
|
* Native callback class for main-thread callbacks.
|
|
643
649
|
* @category Callbacks
|
|
@@ -1197,8 +1203,10 @@ export interface PointerInstance<T = any> {
|
|
|
1197
1203
|
* @category Pointers
|
|
1198
1204
|
*/
|
|
1199
1205
|
export interface PointerTypeDef<T = any> {
|
|
1200
|
-
/** The type
|
|
1201
|
-
readonly _pointerTo:
|
|
1206
|
+
/** The resolved base type, including for lazy pointer declarations. */
|
|
1207
|
+
readonly _pointerTo: T;
|
|
1208
|
+
/** Python ctypes alias for the resolved base type. */
|
|
1209
|
+
readonly _type_: T;
|
|
1202
1210
|
/** Size of the pointed-to type. */
|
|
1203
1211
|
readonly _baseSize: number;
|
|
1204
1212
|
/** Pointer size (always 8 on 64-bit). */
|
|
@@ -1640,12 +1648,12 @@ export interface FuncPtrFactory<TRet extends FFIType | null = FFIType | null, TA
|
|
|
1640
1648
|
(address: bigint | number): TypedFFIFunction<TArgs, TRet>;
|
|
1641
1649
|
new (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
|
|
1642
1650
|
/**
|
|
1643
|
-
* Call with a JS function to produce a
|
|
1644
|
-
* as argument or struct field
|
|
1651
|
+
* Call with a JS function to produce a directly callable, typed C callback,
|
|
1652
|
+
* usable as an argument or struct field. Keep it referenced while C may
|
|
1645
1653
|
* call it; `release()` frees it.
|
|
1646
1654
|
*/
|
|
1647
|
-
(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>):
|
|
1648
|
-
new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>):
|
|
1655
|
+
(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
|
|
1656
|
+
new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
|
|
1649
1657
|
/**
|
|
1650
1658
|
* Bind an exported function of a library, optionally with paramflags.
|
|
1651
1659
|
* Python: `prototype((name, dll))` / `prototype((name, dll), paramflags)`.
|
|
@@ -2011,9 +2019,10 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, o
|
|
|
2011
2019
|
* When the target is a {@link PointerTypeDef}, returns a {@link PointerInstance} with
|
|
2012
2020
|
* `.contents` and `[index]` access — equivalent to Python's
|
|
2013
2021
|
* `cast(c_void_p(addr), POINTER(MyStruct))`.
|
|
2022
|
+
* A {@link FuncPtrFactory} target returns a caller with that prototype.
|
|
2014
2023
|
*
|
|
2015
|
-
* @param ptr -
|
|
2016
|
-
* @param targetType - The target type (primitive, struct, or
|
|
2024
|
+
* @param ptr - Memory, a pointer/address, or a native function/callback
|
|
2025
|
+
* @param targetType - The target type (primitive, struct, POINTER or CFUNCTYPE)
|
|
2017
2026
|
*
|
|
2018
2027
|
* @example Cast to POINTER for typed array access
|
|
2019
2028
|
* ```javascript
|
|
@@ -2031,8 +2040,11 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, o
|
|
|
2031
2040
|
*
|
|
2032
2041
|
* @category Pointers
|
|
2033
2042
|
*/
|
|
2034
|
-
|
|
2035
|
-
export function cast(ptr:
|
|
2043
|
+
type CastSource = MemorySource | ArrayBuffer | ByRefAddress | FFIFunction | CallbackWrapper | null;
|
|
2044
|
+
export function cast<T>(ptr: CastSource, targetType: PointerTypeDef<T>): PointerInstance<T>;
|
|
2045
|
+
export function cast<TRet extends FFIType | null, TArgs extends readonly FFIType[]>(ptr: CastSource, targetType: FuncPtrFactory<TRet, TArgs>): TypedFFIFunction<TArgs, TRet>;
|
|
2046
|
+
export function cast<T extends SimpleCDataConstructor<"pointer"> | SimpleCDataConstructor<"string"> | SimpleCDataConstructor<"wstring">>(ptr: CastSource, targetType: T): InstanceType<T>;
|
|
2047
|
+
export function cast(ptr: CastSource, targetType: AnyType | StructDef | StructureClass): any;
|
|
2036
2048
|
|
|
2037
2049
|
/**
|
|
2038
2050
|
* Create a pointer type for a given base type.
|
|
@@ -2091,6 +2103,7 @@ export function POINTER<T extends AnyType | StructureClass>(baseType: () => T):
|
|
|
2091
2103
|
*
|
|
2092
2104
|
* @category Pointers
|
|
2093
2105
|
*/
|
|
2106
|
+
export function pointer<T>(obj: PointerInstance<T>): PointerInstance<PointerTypeDef<T>>;
|
|
2094
2107
|
export function pointer<T extends Structure<any>>(obj: T): PointerInstance<new (...args: any[]) => T>;
|
|
2095
2108
|
export function pointer<V>(obj: SimpleCDataInstance<V>): PointerInstance;
|
|
2096
2109
|
export function pointer(obj: Buffer | { _buffer: Buffer }): PointerInstance;
|
|
@@ -2238,7 +2251,7 @@ export type JsFromTag<Tag extends string> = Tag extends "void"
|
|
|
2238
2251
|
: Tag extends "wstring"
|
|
2239
2252
|
? string | null
|
|
2240
2253
|
: Tag extends "pointer"
|
|
2241
|
-
? bigint |
|
|
2254
|
+
? bigint | null
|
|
2242
2255
|
: any;
|
|
2243
2256
|
|
|
2244
2257
|
/**
|
package/lib/memory/buffer.js
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
import { mirrorAddress } from "./mirror.js";
|
|
31
31
|
import { resolveParameter } from "../structures/helpers/common.js";
|
|
32
|
+
import { ArgumentError } from "../platform/errors.js";
|
|
32
33
|
|
|
33
34
|
// Fixed backing stores do not move; resizable/growable stores are never cached.
|
|
34
35
|
const memoryAddresses = new WeakMap();
|
|
@@ -411,7 +412,19 @@ export function create_unicode_buffer(init, size, native) {
|
|
|
411
412
|
* ```
|
|
412
413
|
*/
|
|
413
414
|
export function string_at(address, size, native) {
|
|
414
|
-
|
|
415
|
+
const source = stringSource(address, native);
|
|
416
|
+
if (typeof size === "number" && Number.isFinite(size) && size >= 0) {
|
|
417
|
+
const length = Math.trunc(size);
|
|
418
|
+
if (length === 0) return "";
|
|
419
|
+
if (source === null || source === undefined) return null;
|
|
420
|
+
// Sized reads are binary: Latin1 preserves every byte as one JS code unit.
|
|
421
|
+
if (Buffer.isBuffer(source)) {
|
|
422
|
+
if (length > source.length) throw new RangeError("size exceeds the buffer length");
|
|
423
|
+
return source.toString("latin1", 0, length);
|
|
424
|
+
}
|
|
425
|
+
return native.ptrToBuffer(source, length)?.toString("latin1") ?? null;
|
|
426
|
+
}
|
|
427
|
+
return native.readCString(source, size);
|
|
415
428
|
}
|
|
416
429
|
|
|
417
430
|
/**
|
|
@@ -449,10 +462,15 @@ export function wstring_at(address, size, native) {
|
|
|
449
462
|
*/
|
|
450
463
|
function stringSource(value, native) {
|
|
451
464
|
if (value === null || value === undefined || typeof value === "bigint" || typeof value === "number") return value;
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
465
|
+
try {
|
|
466
|
+
// Array proxies pass Buffer.isBuffer but are resolved through _buffer.
|
|
467
|
+
if (Buffer.isBuffer(value) && value._buffer === undefined) return mirrorAddress(value) ?? value;
|
|
468
|
+
const memory = memoryOf(value, native, "address", true);
|
|
469
|
+
return memory instanceof Uint8Array && !Buffer.isBuffer(memory) ? Buffer.from(memory.buffer, memory.byteOffset, memory.byteLength) : memory;
|
|
470
|
+
} catch (error) {
|
|
471
|
+
if (error instanceof ArgumentError) throw error;
|
|
472
|
+
throw new ArgumentError(`argument 1: ${error?.name ?? "Error"}: ${error?.message ?? String(error)}`, { cause: error });
|
|
473
|
+
}
|
|
456
474
|
}
|
|
457
475
|
|
|
458
476
|
/**
|