node-ctypes 2.1.1 → 2.3.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/README.md +98 -13
- 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 +86 -76
- package/lib/core/callback.js +10 -17
- package/lib/core/conversions.js +193 -3
- package/lib/core/funcptr.js +67 -52
- package/lib/core/lazy-loader.js +10 -4
- package/lib/core/types.js +196 -98
- package/lib/index.d.ts +193 -47
- package/lib/index.js +51 -28
- package/lib/memory/buffer.js +66 -19
- package/lib/memory/mirror.js +283 -0
- package/lib/memory/operations.js +59 -42
- package/lib/memory/pointer.js +180 -61
- package/lib/platform/constants.js +0 -1
- package/lib/platform/errors.js +48 -4
- package/lib/platform/find_library.js +78 -19
- package/lib/structures/Structure.js +260 -172
- package/lib/structures/Union.js +10 -21
- package/lib/structures/helpers/array.js +235 -92
- package/lib/structures/helpers/bitfield.js +66 -150
- package/lib/structures/helpers/common.js +115 -15
- package/lib/structures/helpers/layout.js +131 -0
- package/lib/structures/helpers/struct.js +144 -400
- package/lib/structures/helpers/union.js +132 -142
- package/lib/structures/helpers/wrap.js +29 -17
- package/lib/types/SimpleCData.js +14 -7
- package/lib/types/primitives.js +130 -101
- package/package.json +2 -1
package/lib/core/conversions.js
CHANGED
|
@@ -6,11 +6,18 @@
|
|
|
6
6
|
* conversion).
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
|
|
10
|
+
import { ArgumentError } from "../platform/errors.js";
|
|
11
|
+
import { encodeWide } from "../memory/buffer.js";
|
|
12
|
+
import { buildWrapper } from "../structures/helpers/wrap.js";
|
|
13
|
+
|
|
9
14
|
/**
|
|
10
15
|
* Base conversion of an object argument:
|
|
11
16
|
* - struct/union/array instance or Buffer view → its Buffer (by reference)
|
|
12
17
|
* - pointer created from an address → the address
|
|
13
18
|
* - object with `_as_parameter_` (callbacks, adapters) → that value
|
|
19
|
+
* - copy of native memory (no external buffers, memory/mirror.js) → the
|
|
20
|
+
* original address
|
|
14
21
|
* - anything else unchanged
|
|
15
22
|
*/
|
|
16
23
|
export function coerceObject(a) {
|
|
@@ -20,12 +27,50 @@ export function coerceObject(a) {
|
|
|
20
27
|
// Puntatore creato da indirizzo (fromAddress): senza Buffer va passato
|
|
21
28
|
// l'indirizzo, altrimenti al C arriverebbe NULL.
|
|
22
29
|
if (b === null && a._pointerType !== undefined) return a.address;
|
|
30
|
+
if (mirrorsActive) return mirrorAddress(b) ?? b;
|
|
23
31
|
return b;
|
|
24
32
|
}
|
|
25
33
|
if (a._as_parameter_ !== undefined) return a._as_parameter_;
|
|
34
|
+
if (mirrorsActive) return mirrorAddress(a) ?? a;
|
|
26
35
|
return a;
|
|
27
36
|
}
|
|
28
37
|
|
|
38
|
+
// Struct/union passato per valore: il nativo copia i byte del Buffer, che per
|
|
39
|
+
// una copia di memoria nativa vanno prima riletti.
|
|
40
|
+
function coerceStructValue(a) {
|
|
41
|
+
if (a !== null && typeof a === "object") {
|
|
42
|
+
const b = Buffer.isBuffer(a._buffer) ? a._buffer : a;
|
|
43
|
+
if (Buffer.isBuffer(b)) {
|
|
44
|
+
refresh(b);
|
|
45
|
+
return b;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return coerceObject(a);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const isStructType = (t) => t !== null && (typeof t === "function" || typeof t === "object") && (typeof t._buildStruct === "function" || typeof t._buildUnion === "function" || t._isStructType === true);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Converter for a struct/union passed by value. A plain object (fields by
|
|
55
|
+
* name, a node-ctypes extension) becomes an instance of the type first, so
|
|
56
|
+
* bit fields and fields of `_pack_` layouts (which the native description
|
|
57
|
+
* holds as bytes) get their values. An array is rejected, as a Python tuple.
|
|
58
|
+
*/
|
|
59
|
+
function structArgument(T, index) {
|
|
60
|
+
const instance = typeof T === "function" ? (values) => new T(values) : (values) => T.create(values);
|
|
61
|
+
const coerce = mirrorsActive ? coerceStructValue : coerceObject;
|
|
62
|
+
return (a) => {
|
|
63
|
+
if (Array.isArray(a)) {
|
|
64
|
+
// Python rifiuta anche una tupla.
|
|
65
|
+
throw new ArgumentError(`argument ${index + 1}: TypeError: expected ${T.name || "structure"} instance instead of Array`);
|
|
66
|
+
}
|
|
67
|
+
if (a !== null && typeof a === "object" && a._buffer === undefined && a._as_parameter_ === undefined && !ArrayBuffer.isView(a) && !(a instanceof ArrayBuffer)) {
|
|
68
|
+
return coerce(instance(a));
|
|
69
|
+
}
|
|
70
|
+
return coerce(a);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
29
74
|
/**
|
|
30
75
|
* Python default conversion (no argtypes, variadic arguments): a SimpleCData
|
|
31
76
|
* instance is passed by value (`abs(c_int(-5))`), other objects as
|
|
@@ -37,6 +82,16 @@ export function coerceValue(a) {
|
|
|
37
82
|
return coerceObject(a);
|
|
38
83
|
}
|
|
39
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Conversion of an argument beyond `argtypes` (variadic, or without
|
|
87
|
+
* argtypes): a SimpleCData instance is passed as is, and the native call uses
|
|
88
|
+
* its type, as Python does (`printf("%f", c_double(2.0))`).
|
|
89
|
+
*/
|
|
90
|
+
export function coerceVariadic(a) {
|
|
91
|
+
if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return a;
|
|
92
|
+
return coerceObject(a);
|
|
93
|
+
}
|
|
94
|
+
|
|
40
95
|
/**
|
|
41
96
|
* Argument converters for `argtypes`, one per position. A SimpleCData instance
|
|
42
97
|
* passed to a simple-type parameter is its value; to a pointer-like parameter
|
|
@@ -49,7 +104,9 @@ export function coerceValue(a) {
|
|
|
49
104
|
*/
|
|
50
105
|
export function argumentConverters(argTypes, native) {
|
|
51
106
|
const pointerKinds = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
|
|
52
|
-
|
|
107
|
+
const baseConverter = (t, index) => {
|
|
108
|
+
if (isStructType(t)) return structArgument(t, index);
|
|
109
|
+
if (t !== null && (typeof t === "function" || typeof t === "object") && t._isArrayType === true) return arrayArgument(t, index);
|
|
53
110
|
if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
|
|
54
111
|
if (!pointerKinds.has(t._type)) return coerceValue;
|
|
55
112
|
return (a) => {
|
|
@@ -57,9 +114,68 @@ export function argumentConverters(argTypes, native) {
|
|
|
57
114
|
if (a._isSimpleCDataInstance === true && a instanceof t) return a.value;
|
|
58
115
|
return coerceObject(a);
|
|
59
116
|
};
|
|
117
|
+
};
|
|
118
|
+
return argTypes.map((t, index) => {
|
|
119
|
+
const base = baseConverter(t, index);
|
|
120
|
+
if (t === null || (typeof t !== "function" && typeof t !== "object") || typeof t.from_param !== "function") return base;
|
|
121
|
+
return fromParamArgument(t, base, index);
|
|
60
122
|
});
|
|
61
123
|
}
|
|
62
124
|
|
|
125
|
+
/**
|
|
126
|
+
* Converter for an argtype with a `from_param` method (Python protocol): it
|
|
127
|
+
* receives the argument as passed, its result (or the result's
|
|
128
|
+
* `_as_parameter_`) is converted as the declared type. Its errors become
|
|
129
|
+
* ArgumentError "argument N: <name>: <message>", as in Python.
|
|
130
|
+
*/
|
|
131
|
+
function fromParamArgument(T, base, index) {
|
|
132
|
+
return (a) => {
|
|
133
|
+
let converted;
|
|
134
|
+
try {
|
|
135
|
+
converted = T.from_param(a);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
if (e instanceof ArgumentError) throw e;
|
|
138
|
+
throw new ArgumentError(`argument ${index + 1}: ${e?.name ?? "Error"}: ${e?.message ?? String(e)}`, { cause: e });
|
|
139
|
+
}
|
|
140
|
+
return base(converted);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const arrayTypeName = (T) => `${T.elementType?.name || "array"} * ${T.length}`;
|
|
145
|
+
|
|
146
|
+
function describeValue(a) {
|
|
147
|
+
if (a === null) return "null";
|
|
148
|
+
if (typeof a !== "object") return typeof a;
|
|
149
|
+
if (a._arrayType !== undefined) return arrayTypeName(a._arrayType);
|
|
150
|
+
return a.constructor?.name ?? "object";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Converter for an array parameter (`argtypes = [c_int * 4]`): the array is
|
|
155
|
+
* passed by address, as in C and Python. As Python, only instances of the
|
|
156
|
+
* same array type (element type and length) are accepted; Buffers and typed
|
|
157
|
+
* arrays are also accepted as memory.
|
|
158
|
+
*
|
|
159
|
+
* @param {Function} T - Array type
|
|
160
|
+
* @param {number} index - Parameter position (for the error message)
|
|
161
|
+
* @returns {Function} Converter
|
|
162
|
+
*/
|
|
163
|
+
function arrayArgument(T, index) {
|
|
164
|
+
return (a) => {
|
|
165
|
+
if (a !== null && typeof a === "object") {
|
|
166
|
+
const arrayType = a._arrayType;
|
|
167
|
+
if (arrayType !== undefined) {
|
|
168
|
+
if (arrayType === T || (arrayType.elementType === T.elementType && arrayType.length === T.length)) return coerceObject(a);
|
|
169
|
+
} else if (ArrayBuffer.isView(a) || a instanceof ArrayBuffer) {
|
|
170
|
+
return coerceObject(a);
|
|
171
|
+
} else if (a._as_parameter_ !== undefined) {
|
|
172
|
+
return a._as_parameter_;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
throw new ArgumentError(`argument ${index + 1}: TypeError: expected ${arrayTypeName(T)} instance instead of ${describeValue(a)}`);
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
63
179
|
/**
|
|
64
180
|
* Convert all call arguments: declared ones with their converter, the rest
|
|
65
181
|
* (variadic or without argtypes) with the Python default conversion.
|
|
@@ -69,7 +185,7 @@ export function convertArguments(args, converters) {
|
|
|
69
185
|
const declared = converters.length;
|
|
70
186
|
const out = new Array(n);
|
|
71
187
|
for (let i = 0; i < n; i++) {
|
|
72
|
-
out[i] = i < declared ? converters[i](args[i]) :
|
|
188
|
+
out[i] = i < declared ? converters[i](args[i]) : coerceVariadic(args[i]);
|
|
73
189
|
}
|
|
74
190
|
return out;
|
|
75
191
|
}
|
|
@@ -89,9 +205,35 @@ export function resultConverter(restype) {
|
|
|
89
205
|
if (typeof restype === "function" && restype._isFuncPtr === true) {
|
|
90
206
|
return (r) => (r === null || r === 0n ? null : restype(r));
|
|
91
207
|
}
|
|
208
|
+
// Struct/union per valore: il nativo restituisce i byte (opzione
|
|
209
|
+
// `struct_buffer`, vedi structResult) in un Buffer riusato dalla funzione
|
|
210
|
+
// a ogni chiamata, copiato qui nella memoria dell'istanza. Python:
|
|
211
|
+
// un'istanza della classe.
|
|
212
|
+
if (typeof restype === "function" && typeof restype._buildStruct === "function") {
|
|
213
|
+
return (r) => {
|
|
214
|
+
const bytes = Buffer.alloc(r.length);
|
|
215
|
+
bytes.set(r);
|
|
216
|
+
return new restype(bytes);
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
if (restype !== null && typeof restype === "object" && restype._isStructType === true) {
|
|
220
|
+
return (r) => restype.toObject(r);
|
|
221
|
+
}
|
|
92
222
|
return undefined;
|
|
93
223
|
}
|
|
94
224
|
|
|
225
|
+
/**
|
|
226
|
+
* True when `restype` is a struct or union returned by value: the native
|
|
227
|
+
* function must then return its bytes (FFIFunction option `struct_buffer`),
|
|
228
|
+
* which {@link resultConverter} turns into the result.
|
|
229
|
+
*
|
|
230
|
+
* @param {*} restype - Declared return type
|
|
231
|
+
* @returns {boolean}
|
|
232
|
+
*/
|
|
233
|
+
export function structResult(restype) {
|
|
234
|
+
return (typeof restype === "function" && typeof restype._buildStruct === "function") || (restype !== null && typeof restype === "object" && restype._isStructType === true);
|
|
235
|
+
}
|
|
236
|
+
|
|
95
237
|
/**
|
|
96
238
|
* Adapt a JS function used as a C callback to Python semantics: arguments
|
|
97
239
|
* declared `POINTER(T)` are passed as pointer objects (`null` for NULL), and an
|
|
@@ -102,9 +244,13 @@ export function resultConverter(restype) {
|
|
|
102
244
|
* @param {Array} argTypes - Declared argument types
|
|
103
245
|
* @returns {Function} Function to register with the native callback
|
|
104
246
|
*/
|
|
105
|
-
export function adaptCallbackFunction(fn, argTypes) {
|
|
247
|
+
export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
106
248
|
const pointerTypes = argTypes.map((t) => (t !== null && typeof t === "object" && t._pointerTo !== undefined ? t : null));
|
|
107
249
|
const hasPointers = pointerTypes.some((t) => t !== null);
|
|
250
|
+
// Struct/union per valore: il nativo passa una copia in un Buffer.
|
|
251
|
+
const structViews = argTypes.map(structView);
|
|
252
|
+
const hasStructs = structViews.some((view) => view !== null);
|
|
253
|
+
const toResult = stringResult(returnType, native);
|
|
108
254
|
return function (...args) {
|
|
109
255
|
if (hasPointers) {
|
|
110
256
|
for (let i = 0; i < pointerTypes.length; i++) {
|
|
@@ -114,7 +260,51 @@ export function adaptCallbackFunction(fn, argTypes) {
|
|
|
114
260
|
}
|
|
115
261
|
}
|
|
116
262
|
}
|
|
263
|
+
if (hasStructs) {
|
|
264
|
+
for (let i = 0; i < structViews.length; i++) {
|
|
265
|
+
if (structViews[i] !== null) args[i] = structViews[i](args[i]);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
117
268
|
const result = fn.apply(this, args);
|
|
269
|
+
if (toResult !== undefined && typeof result === "string") return toResult(result);
|
|
118
270
|
return result !== null && typeof result === "object" ? coerceValue(result) : result;
|
|
119
271
|
};
|
|
120
272
|
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* View of a struct/union argument of a callback (Buffer with a copy of the
|
|
276
|
+
* C value): an instance of the class, or of the struct()/union() definition.
|
|
277
|
+
*
|
|
278
|
+
* @returns {Function|null} Converter, null for other argument types
|
|
279
|
+
*/
|
|
280
|
+
function structView(type) {
|
|
281
|
+
if (typeof type === "function" && typeof type._buildStruct === "function") return (buf) => new type(buf);
|
|
282
|
+
if (type !== null && typeof type === "object" && type._isStructType === true) {
|
|
283
|
+
return (buf) => new Proxy(buf, buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true }));
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Result of a callback whose restype is c_char_p / c_wchar_p and that returns
|
|
290
|
+
* a JS string: a NUL-terminated buffer, kept alive as long as the callback
|
|
291
|
+
* (Python keeps it forever, with "RuntimeWarning: memory leak in callback
|
|
292
|
+
* function"). Buffers are cached by value, so a callback that returns the
|
|
293
|
+
* same strings does not accumulate memory.
|
|
294
|
+
*
|
|
295
|
+
* @returns {Function|undefined} Converter, undefined for other restypes
|
|
296
|
+
*/
|
|
297
|
+
function stringResult(returnType, native) {
|
|
298
|
+
if (native === undefined || typeof returnType !== "function" || returnType._isSimpleCData !== true) return undefined;
|
|
299
|
+
const wide = returnType._type === native.CType.WSTRING;
|
|
300
|
+
if (!wide && returnType._type !== native.CType.STRING) return undefined;
|
|
301
|
+
const kept = new Map();
|
|
302
|
+
return (value) => {
|
|
303
|
+
let buf = kept.get(value);
|
|
304
|
+
if (buf === undefined) {
|
|
305
|
+
buf = wide ? Buffer.concat([encodeWide(value, native.WCHAR_SIZE), Buffer.alloc(native.WCHAR_SIZE)]) : Buffer.from(`${value}\0`, "utf8");
|
|
306
|
+
kept.set(value, buf);
|
|
307
|
+
}
|
|
308
|
+
return buf;
|
|
309
|
+
};
|
|
310
|
+
}
|
package/lib/core/funcptr.js
CHANGED
|
@@ -25,21 +25,19 @@
|
|
|
25
25
|
*
|
|
26
26
|
* @example COM vtable dispatch
|
|
27
27
|
* ```javascript
|
|
28
|
-
* import { WINFUNCTYPE, c_int32, c_void_p
|
|
28
|
+
* import { WINFUNCTYPE, POINTER, c_int32, c_void_p } from 'node-ctypes';
|
|
29
29
|
*
|
|
30
|
-
* //
|
|
31
|
-
* const
|
|
32
|
-
* const vtableAddr = vtableBuf.readBigUInt64LE(0);
|
|
33
|
-
* const vtable = ptrToBuffer(vtableAddr, 24); // 3 IUnknown methods * 8 bytes
|
|
30
|
+
* // The first field of a COM object is the address of its vtable
|
|
31
|
+
* const vtable = POINTER(c_void_p).fromAddress(c_void_p.from_address(objPtr).value);
|
|
34
32
|
*
|
|
35
33
|
* // QueryInterface is the first vtable entry
|
|
36
34
|
* const QueryInterface = WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p);
|
|
37
|
-
* const qi = QueryInterface(vtable
|
|
35
|
+
* const qi = QueryInterface(vtable[0]);
|
|
38
36
|
* ```
|
|
39
37
|
*/
|
|
40
38
|
|
|
41
39
|
import { _toNativeReturnType, _toNativeTypes } from "./types.js";
|
|
42
|
-
import { argumentConverters, convertArguments, resultConverter } from "./conversions.js";
|
|
40
|
+
import { argumentConverters, convertArguments, resultConverter, structResult } from "./conversions.js";
|
|
43
41
|
import { callback as createCallback } from "./callback.js";
|
|
44
42
|
|
|
45
43
|
/**
|
|
@@ -60,7 +58,9 @@ import { callback as createCallback } from "./callback.js";
|
|
|
60
58
|
* - N out params → array di N elementi [out1, out2, ...].
|
|
61
59
|
*
|
|
62
60
|
* Quando ci sono out params, `result` (restype) NON appare nel return.
|
|
63
|
-
* Se serve ispezionarlo usa `.errcheck = fn` che riceve (result, func, args)
|
|
61
|
+
* Se serve ispezionarlo usa `.errcheck = fn` che riceve (result, func, args),
|
|
62
|
+
* con le istanze "out" in args; il valore restituito da errcheck diventa il
|
|
63
|
+
* risultato, salvo `args` stesso (allora il risultato sono le out).
|
|
64
64
|
*
|
|
65
65
|
* @private
|
|
66
66
|
*/
|
|
@@ -87,7 +87,9 @@ function applyParamflags(rawFn, restype, argtypes, paramflags) {
|
|
|
87
87
|
const inputs = slots.filter((s) => s.dir !== "out");
|
|
88
88
|
const outputs = slots.filter((s) => s.dir === "out");
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
let errcheck = null;
|
|
91
|
+
|
|
92
|
+
const paramflagsWrapper = function (...callArgs) {
|
|
91
93
|
const namedForm =
|
|
92
94
|
callArgs.length === 1 &&
|
|
93
95
|
callArgs[0] !== null &&
|
|
@@ -98,7 +100,6 @@ function applyParamflags(rawFn, restype, argtypes, paramflags) {
|
|
|
98
100
|
callArgs[0]._buffer === undefined;
|
|
99
101
|
|
|
100
102
|
const rawArgs = new Array(slots.length);
|
|
101
|
-
const outBuffers = [];
|
|
102
103
|
|
|
103
104
|
// Populate in-slots
|
|
104
105
|
let posIdx = 0;
|
|
@@ -116,54 +117,60 @@ function applyParamflags(rawFn, restype, argtypes, paramflags) {
|
|
|
116
117
|
rawArgs[input.idx] = value;
|
|
117
118
|
}
|
|
118
119
|
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if (t._isSimpleCData) {
|
|
127
|
-
baseSize = t._size;
|
|
128
|
-
} else if (typeof t === "function" && (typeof t._buildStruct === "function" || typeof t._buildUnion === "function")) {
|
|
129
|
-
const def = t._structDef || t._unionDef || t._buildStruct?.() || t._buildUnion?.();
|
|
130
|
-
baseSize = def?.size;
|
|
131
|
-
} else if (t && typeof t === "object" && typeof t.size === "number") {
|
|
132
|
-
baseSize = t.size;
|
|
133
|
-
}
|
|
134
|
-
if (!baseSize || baseSize <= 0) {
|
|
135
|
-
throw new TypeError(`paramflags "out" param "${output.name}": cannot determine size of target type`);
|
|
136
|
-
}
|
|
137
|
-
const buf = Buffer.alloc(baseSize);
|
|
138
|
-
outBuffers.push({ buf, type: t, name: output.name });
|
|
139
|
-
rawArgs[output.idx] = buf;
|
|
140
|
-
}
|
|
120
|
+
// Python: un parametro "out" è un'istanza del tipo puntato, passata per
|
|
121
|
+
// riferimento (il suo Buffer).
|
|
122
|
+
const outs = outputs.map((output) => {
|
|
123
|
+
const instance = newOutInstance(output.outType, output.name);
|
|
124
|
+
rawArgs[output.idx] = instance;
|
|
125
|
+
return { instance, type: output.outType };
|
|
126
|
+
});
|
|
141
127
|
|
|
142
128
|
const result = rawFn(...rawArgs);
|
|
143
129
|
|
|
144
|
-
|
|
130
|
+
// Python: errcheck(result, func, args) riceve anche le istanze "out"; il
|
|
131
|
+
// valore restituito è il risultato, salvo `args` stesso (allora le out).
|
|
132
|
+
if (errcheck !== null) {
|
|
133
|
+
const checked = errcheck(result, paramflagsWrapper, rawArgs);
|
|
134
|
+
if (checked !== rawArgs) return checked;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (outs.length === 0) return result;
|
|
145
138
|
|
|
146
|
-
// Read-back per type: SimpleCData → _reader, Structure/Union → instance
|
|
147
|
-
// wrapper, plain def → toObject.
|
|
148
|
-
const outs = outBuffers.map(({ buf, type }) => {
|
|
149
|
-
if (type._isSimpleCData) return type._reader(buf, 0);
|
|
150
|
-
if (typeof type === "function" && (typeof type._buildStruct === "function" || typeof type._buildUnion === "function")) {
|
|
151
|
-
// Istanzia la classe wrappando il buffer (zero-copy se Structure).
|
|
152
|
-
return new type(buf);
|
|
153
|
-
}
|
|
154
|
-
if (type && typeof type === "object" && typeof type.toObject === "function") {
|
|
155
|
-
return type.toObject(buf);
|
|
156
|
-
}
|
|
157
|
-
// Fallback: ritorna il buffer raw.
|
|
158
|
-
return buf;
|
|
159
|
-
});
|
|
160
139
|
// Python ctypes parity: quando ci sono out-params il return value è
|
|
161
140
|
// SOLO le outs (singolo valore se 1, array se >1) — indipendentemente
|
|
162
|
-
// da restype
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
141
|
+
// da restype: il valore per i tipi semplici, l'istanza per Structure/Union.
|
|
142
|
+
const values = outs.map(({ instance, type }) => {
|
|
143
|
+
if (type._isSimpleCData) return instance.value;
|
|
144
|
+
if (typeof type === "function") return instance;
|
|
145
|
+
return type.toObject(instance._buffer);
|
|
146
|
+
});
|
|
147
|
+
return values.length === 1 ? values[0] : values;
|
|
166
148
|
};
|
|
149
|
+
|
|
150
|
+
Object.defineProperty(paramflagsWrapper, "errcheck", {
|
|
151
|
+
get: () => errcheck,
|
|
152
|
+
set: (callback) => {
|
|
153
|
+
if (callback !== null && callback !== undefined && typeof callback !== "function") {
|
|
154
|
+
throw new TypeError("errcheck must be a function or null");
|
|
155
|
+
}
|
|
156
|
+
errcheck = callback ?? null;
|
|
157
|
+
},
|
|
158
|
+
enumerable: false,
|
|
159
|
+
configurable: true,
|
|
160
|
+
});
|
|
161
|
+
return paramflagsWrapper;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Istanza per un parametro "out": SimpleCData, Structure/Union class o
|
|
165
|
+
// definizione struct()/union().
|
|
166
|
+
function newOutInstance(type, name) {
|
|
167
|
+
if (typeof type === "function" && (type._isSimpleCData || typeof type._buildStruct === "function")) {
|
|
168
|
+
return new type();
|
|
169
|
+
}
|
|
170
|
+
if (type && typeof type === "object" && typeof type.create === "function") {
|
|
171
|
+
return type.create();
|
|
172
|
+
}
|
|
173
|
+
throw new TypeError(`paramflags "out" param "${name}": cannot determine the target type`);
|
|
167
174
|
}
|
|
168
175
|
|
|
169
176
|
/**
|
|
@@ -225,6 +232,7 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
225
232
|
}
|
|
226
233
|
// Python: prototype((name, dll)) / prototype((name, dll), paramflags)
|
|
227
234
|
// binds an exported function of a library to this prototype.
|
|
235
|
+
let ownerLibrary;
|
|
228
236
|
if (Array.isArray(addressOrFn)) {
|
|
229
237
|
const [name, library] = addressOrFn;
|
|
230
238
|
if (typeof name !== "string" || library === null || typeof library !== "object" || typeof library.symbol !== "function") {
|
|
@@ -233,6 +241,9 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
233
241
|
if (paramflags !== undefined) {
|
|
234
242
|
return factory.bind(library, name, paramflags);
|
|
235
243
|
}
|
|
244
|
+
// La funzione tiene caricata la libreria del simbolo (come CDLL.func).
|
|
245
|
+
const nativeLibrary = library._lib ?? library;
|
|
246
|
+
if (nativeLibrary instanceof native.Library) ownerLibrary = nativeLibrary;
|
|
236
247
|
addressOrFn = library.symbol(name);
|
|
237
248
|
}
|
|
238
249
|
// Python accetta l'indirizzo come int: anche qui number o BigInt.
|
|
@@ -241,7 +252,11 @@ function createFuncPtrType(native, typeName, abi) {
|
|
|
241
252
|
throw new TypeError(`${typeName}: argument must be an address (BigInt or number), a JS function or [name, library]`);
|
|
242
253
|
}
|
|
243
254
|
|
|
244
|
-
const
|
|
255
|
+
const options = {};
|
|
256
|
+
if (abi) options.abi = abi;
|
|
257
|
+
if (ownerLibrary) options.library = ownerLibrary;
|
|
258
|
+
if (structResult(restype)) options.struct_buffer = true;
|
|
259
|
+
const ffiFunc = new native.FFIFunction(address, null, nativeRestype, nativeArgtypes, options);
|
|
245
260
|
|
|
246
261
|
// Come le funzioni di CDLL: restype POINTER/CFUNCTYPE convertito, ed
|
|
247
262
|
// errcheck applicato sul valore convertito.
|
package/lib/core/lazy-loader.js
CHANGED
|
@@ -37,23 +37,29 @@
|
|
|
37
37
|
* @param {Function} DllClass - CDLL, WinDLL, or OleDLL constructor.
|
|
38
38
|
* @returns {Proxy} Namespace object with `.<libname>` auto-loading.
|
|
39
39
|
*/
|
|
40
|
+
// Proprietà interrogate da String(), JSON.stringify, util.inspect, test
|
|
41
|
+
// runner e framework: non sono nomi di librerie.
|
|
42
|
+
const probes = new Set(["then", "toJSON", "valueOf", "constructor", "inspect", "nodeType", "asymmetricMatch", "$$typeof"]);
|
|
43
|
+
|
|
40
44
|
export function createLazyLoader(DllClass) {
|
|
41
45
|
const cache = new Map();
|
|
42
46
|
// Python: cdll.LoadLibrary(name, ...) crea sempre una nuova istanza.
|
|
43
47
|
const LoadLibrary = (name, ...args) => new DllClass(name, ...args);
|
|
48
|
+
const toString = () => `[object LibraryLoader ${DllClass.name}]`;
|
|
49
|
+
// Python LibraryLoader.__getattr__: i nomi che iniziano con "_" non sono librerie.
|
|
50
|
+
const isLibraryName = (name) => typeof name === "string" && name !== "" && name[0] !== "_" && !probes.has(name) && name !== "toString" && name !== "LoadLibrary";
|
|
44
51
|
return new Proxy(Object.create(null), {
|
|
45
52
|
get(_, libName) {
|
|
46
|
-
if (typeof libName !== "string") return undefined;
|
|
47
|
-
// Skip symbol/private probes used by Node's inspect / util.inspect.
|
|
48
|
-
if (libName === "then") return undefined;
|
|
49
53
|
if (libName === "LoadLibrary") return LoadLibrary;
|
|
54
|
+
if (libName === "toString") return toString;
|
|
55
|
+
if (!isLibraryName(libName)) return undefined;
|
|
50
56
|
if (!cache.has(libName)) {
|
|
51
57
|
cache.set(libName, new DllClass(libName));
|
|
52
58
|
}
|
|
53
59
|
return cache.get(libName);
|
|
54
60
|
},
|
|
55
61
|
has(_, libName) {
|
|
56
|
-
return
|
|
62
|
+
return libName === "LoadLibrary" || libName === "toString" || isLibraryName(libName);
|
|
57
63
|
},
|
|
58
64
|
});
|
|
59
65
|
}
|