node-ctypes 2.13.2 → 2.15.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/build/Release/ctypes-darwin-arm64.node +0 -0
  3. package/build/Release/ctypes-darwin-x64.node +0 -0
  4. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  5. package/build/Release/ctypes-linux-arm64.node +0 -0
  6. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  7. package/build/Release/ctypes-linux-x64.node +0 -0
  8. package/build/Release/ctypes-win32-arm64.node +0 -0
  9. package/build/Release/ctypes-win32-x64.node +0 -0
  10. package/lib/core/Library.js +69 -51
  11. package/lib/core/callback-conversions.js +123 -0
  12. package/lib/core/callback.js +68 -4
  13. package/lib/core/conversions.js +74 -412
  14. package/lib/core/funcptr.js +31 -287
  15. package/lib/core/invocation.js +170 -0
  16. package/lib/core/native-aggregate.js +193 -0
  17. package/lib/core/parameters.js +45 -0
  18. package/lib/core/paramflags.js +183 -0
  19. package/lib/core/results.js +86 -0
  20. package/lib/core/types.js +14 -277
  21. package/lib/index.d.ts +3 -0
  22. package/lib/index.js +2 -1
  23. package/lib/memory/buffer.js +1 -1
  24. package/lib/memory/mirror.js +2 -2
  25. package/lib/memory/operations.js +2 -1
  26. package/lib/memory/ownership.js +218 -0
  27. package/lib/memory/pointer.js +6 -1
  28. package/lib/platform/win_types.js +1 -1
  29. package/lib/structures/Structure.js +50 -37
  30. package/lib/structures/helpers/array.js +27 -13
  31. package/lib/structures/helpers/bitfield.js +1 -1
  32. package/lib/structures/helpers/common.js +3 -368
  33. package/lib/structures/helpers/fields.js +111 -0
  34. package/lib/structures/helpers/layout.js +44 -57
  35. package/lib/structures/helpers/struct.js +19 -108
  36. package/lib/structures/helpers/union.js +13 -114
  37. package/lib/structures/helpers/wrap.js +1 -1
  38. package/lib/structures/protocol.js +8 -0
  39. package/lib/types/SimpleCData.js +2 -1
  40. package/lib/types/primitives.js +2 -1
  41. package/lib/types/scalar-protocol.js +120 -0
  42. package/package.json +1 -1
@@ -1,33 +1,18 @@
1
1
  /**
2
2
  * @file conversions.js
3
3
  * @module core/conversions
4
- * @description Argument and result conversions shared by CDLL functions and
5
- * CFUNCTYPE callers, following Python ctypes (`from_param` and restype
6
- * conversion).
4
+ * @description Convert outgoing JS arguments according to their declared ctypes types.
7
5
  */
8
6
 
9
- import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
7
+ import { isMirror, mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
10
8
  import { ArgumentError } from "../platform/errors.js";
11
9
  import { encodeWide } from "../memory/buffer.js";
12
- import { buildWrapper } from "../structures/helpers/wrap.js";
13
- import {
14
- activeArgumentOwners as argumentOwnerRegistry,
15
- activeOwnerStack,
16
- byrefOwners,
17
- isScalarSubclass,
18
- resolveParameter,
19
- scalarArgumentKind,
20
- scalarArgumentSnapshot,
21
- scalarArgumentValue,
22
- scalarInstanceInfo,
23
- scalarView,
24
- structArgumentFactories,
25
- structResultReaders,
26
- } from "../structures/helpers/common.js";
10
+ import { requireDescriptor } from "./types.js";
11
+ import { byrefOwners, resolveParameter } from "./parameters.js";
12
+ import { snapshotArgumentBytes } from "../memory/ownership.js";
13
+ import { structArgumentFactories } from "../structures/protocol.js";
14
+ import { scalarArgumentKind, scalarArgumentSnapshot, scalarArgumentValue, scalarInstanceInfo } from "../types/scalar-protocol.js";
27
15
 
28
- const activeArgumentOwners = argumentOwnerRegistry;
29
- // Captured at load so callback dispatch is not affected by later patches.
30
- const reflectApply = Reflect.apply;
31
16
  function retainArgument(owners, value) {
32
17
  if (owners !== undefined && value !== null && (typeof value === "object" || typeof value === "function")) owners.push(value);
33
18
  }
@@ -40,161 +25,6 @@ export function needsArgumentOwners(value) {
40
25
  return true;
41
26
  }
42
27
 
43
- export function argumentsNeedOwners(args) {
44
- for (let i = 0; i < args.length; i++) if (needsArgumentOwners(args[i])) return true;
45
- return false;
46
- }
47
-
48
- // The general fallback receives the hook snapshot taken before any owner probe.
49
- export function specializeCall(ffiFunc, method, converters, state, invoke, captureHere = true) {
50
- const [C0, C1, C2, C3, C4, C5] = converters;
51
- const [N0, N1, N2, N3, N4, N5] = converters.map((convert) => convert.needsOwners ?? needsArgumentOwners);
52
- const hasAdapters = converters.some((convert) => convert.requiresOwners);
53
- const primitivesPass = converters.every((convert) => convert.passesPrimitives === true);
54
- const sync = method !== "callAsync";
55
- switch (converters.length) {
56
- case 0:
57
- return function () {
58
- const checked = captureHere ? state.errcheck : null;
59
- if (checked !== null || arguments.length !== 0) return invoke(arguments, checked);
60
- return ffiFunc[method]();
61
- };
62
- case 1:
63
- return function (a0) {
64
- const checked = captureHere ? state.errcheck : null;
65
- if (checked !== null || arguments.length !== 1) return invoke(arguments, checked);
66
- if (captureHere && (hasAdapters || N0(a0))) return sync ? callOwned1(ffiFunc, method, C0, a0) : callWithArgumentOwners(ffiFunc, method, arguments, converters);
67
- return ffiFunc[method](C0(a0));
68
- };
69
- case 2:
70
- return function (a0, a1) {
71
- const checked = captureHere ? state.errcheck : null;
72
- if (checked !== null || arguments.length !== 2) return invoke(arguments, checked);
73
- if (captureHere && (hasAdapters || N0(a0) || N1(a1))) return sync ? callOwned2(ffiFunc, method, C0, C1, a0, a1) : callWithArgumentOwners(ffiFunc, method, arguments, converters);
74
- return ffiFunc[method](C0(a0), C1(a1));
75
- };
76
- case 3:
77
- return function (a0, a1, a2) {
78
- const checked = captureHere ? state.errcheck : null;
79
- if (checked !== null || arguments.length !== 3) return invoke(arguments, checked);
80
- if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2))) return sync ? callOwned3(ffiFunc, method, C0, C1, C2, a0, a1, a2) : callWithArgumentOwners(ffiFunc, method, arguments, converters);
81
- return ffiFunc[method](C0(a0), C1(a1), C2(a2));
82
- };
83
- case 4:
84
- return function (a0, a1, a2, a3) {
85
- const checked = captureHere ? state.errcheck : null;
86
- if (checked !== null || arguments.length !== 4) return invoke(arguments, checked);
87
- if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
88
- return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3));
89
- };
90
- case 5:
91
- return function (a0, a1, a2, a3, a4) {
92
- const checked = captureHere ? state.errcheck : null;
93
- if (checked !== null || arguments.length !== 5) return invoke(arguments, checked);
94
- if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3) || N4(a4))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
95
- return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4));
96
- };
97
- case 6:
98
- return function (a0, a1, a2, a3, a4, a5) {
99
- const checked = captureHere ? state.errcheck : null;
100
- if (checked !== null || arguments.length !== 6) return invoke(arguments, checked);
101
- if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3) || N4(a4) || N5(a5))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
102
- return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5));
103
- };
104
- default:
105
- return function () {
106
- const checked = captureHere ? state.errcheck : null;
107
- // Scalar parameters receiving primitives need no conversion and no
108
- // owners: the arguments object goes to the native call as it is.
109
- if (primitivesPass && checked === null && arguments.length === converters.length) {
110
- let primitive = true;
111
- for (let i = 0; i < arguments.length; i++) {
112
- const value = arguments[i];
113
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
114
- primitive = false;
115
- break;
116
- }
117
- }
118
- if (primitive) return reflectApply(ffiFunc[method], ffiFunc, arguments);
119
- }
120
- return invoke(arguments, checked);
121
- };
122
- }
123
- }
124
-
125
- // Synchronous owned calls nest strictly: the owners array is a stack entry
126
- // and the converters run without an intermediate argument array.
127
- function callOwned1(ffiFunc, method, C0, a0) {
128
- const owners = [];
129
- activeOwnerStack.push(owners);
130
- try {
131
- return ffiFunc[method](C0(a0, owners));
132
- } finally {
133
- activeOwnerStack.pop();
134
- }
135
- }
136
-
137
- function callOwned2(ffiFunc, method, C0, C1, a0, a1) {
138
- const owners = [];
139
- activeOwnerStack.push(owners);
140
- try {
141
- return ffiFunc[method](C0(a0, owners), C1(a1, owners));
142
- } finally {
143
- activeOwnerStack.pop();
144
- }
145
- }
146
-
147
- function callOwned3(ffiFunc, method, C0, C1, C2, a0, a1, a2) {
148
- const owners = [];
149
- activeOwnerStack.push(owners);
150
- try {
151
- return ffiFunc[method](C0(a0, owners), C1(a1, owners), C2(a2, owners));
152
- } finally {
153
- activeOwnerStack.pop();
154
- }
155
- }
156
-
157
- // The native asynchronous entry: on the Executor of `call` (callOn: the
158
- // target of this invocation only) or, without it, on the libuv pool.
159
- function invokeAsync(ffiFunc, call, resultHandler, converted) {
160
- if (call === undefined) return resultHandler === undefined ? ffiFunc.callAsync(...converted) : ffiFunc._callAsyncWithErrcheck(resultHandler, ...converted);
161
- return resultHandler === undefined ? ffiFunc.callOn(call, ...converted) : ffiFunc._callOnWithErrcheck(call, resultHandler, ...converted);
162
- }
163
-
164
- // The registry is a GC root, including while another converter reenters JS.
165
- // `call`: the callOn target of an asynchronous call.
166
- export function callWithArgumentOwners(ffiFunc, method, args, converters, finish, resultHandler, checkedCall, call) {
167
- const owners = [];
168
- // Synchronous calls nest strictly, so a stack avoids hashing a fresh array.
169
- activeOwnerStack.push(owners);
170
- try {
171
- const converted = convertArguments(args, converters, owners);
172
- const result =
173
- method === "callAsync"
174
- ? invokeAsync(ffiFunc, call, resultHandler, converted)
175
- : resultHandler === undefined
176
- ? ffiFunc[method](...converted)
177
- : checkedCall === undefined
178
- ? ffiFunc._callWithErrcheck(resultHandler, ...converted)
179
- : checkedCall(resultHandler, ...converted);
180
- if (method === "callAsync") {
181
- const completed = finish === undefined ? result : result.then((value) => finish(value, args));
182
- activeArgumentOwners.add(owners);
183
- return completed.finally(() => activeArgumentOwners.delete(owners));
184
- }
185
- return finish === undefined ? result : finish(result, args);
186
- } finally {
187
- activeOwnerStack.pop();
188
- }
189
- }
190
-
191
- export function callWithResultHandler(ffiFunc, method, args, converters, handler, retainOwners, checkedCall, call) {
192
- if (retainOwners) return callWithArgumentOwners(ffiFunc, method, args, converters, undefined, handler, checkedCall, call);
193
- if (checkedCall !== undefined) return checkedCall(handler, ...convertArguments(args, converters));
194
- if (method === "callAsync") return invokeAsync(ffiFunc, call, handler, convertArguments(args, converters));
195
- return ffiFunc._callWithErrcheck(handler, ...convertArguments(args, converters));
196
- }
197
-
198
28
  /**
199
29
  * Base conversion of an object argument:
200
30
  * - struct/union/array instance or Buffer view → its Buffer (by reference)
@@ -229,15 +59,13 @@ function objectMemory(a, owners) {
229
59
  return a;
230
60
  }
231
61
 
232
- // Struct/union passato per valore: il nativo copia i byte del Buffer, che per
233
- // una copia di memoria nativa vanno prima riletti.
62
+ // By-value arguments need the view, not the native address of its mirror.
234
63
  function coerceStructValue(a, owners) {
235
64
  if (a !== null && typeof a === "object") {
236
65
  retainArgument(owners, a);
237
- const b = Buffer.isBuffer(a._buffer) ? a._buffer : a;
238
- if (Buffer.isBuffer(b)) {
66
+ const b = a._buffer ?? a;
67
+ if (ArrayBuffer.isView(b)) {
239
68
  retainArgument(owners, b);
240
- refresh(b);
241
69
  return b;
242
70
  }
243
71
  }
@@ -253,13 +81,36 @@ const isStructType = (t) => t !== null && (typeof t === "function" || typeof t =
253
81
  * an instance so custom constructors and complex layouts keep their behavior.
254
82
  * An array is rejected, as a Python tuple.
255
83
  */
256
- function structArgument(T, index) {
84
+ function structArgument(T, index, pointerSize) {
85
+ const declaredClass = typeof T === "function" ? T : undefined;
257
86
  const factory = typeof T === "function" ? undefined : structArgumentFactories.get(T);
258
- const instance = typeof T === "function" ? (values) => new T(values) : (factory ?? ((values) => T.create(values)));
259
- const coerce = mirrorsActive ? coerceStructValue : coerceObject;
260
- // The functional struct factory returns its fresh Buffer unconverted.
261
- const build = factory !== undefined && !mirrorsActive ? (values, owners) => factory(values, coerce, owners) : (values, owners) => coerce(instance(values), owners);
262
- const convert = (a, owners) => {
87
+ const instance = typeof T === "function" ? (values) => new T(values) : (values) => T.create(values);
88
+ const memory = mirrorsActive ? coerceStructValue : coerceObject;
89
+ const coerce = (value, owners) => {
90
+ const bytes = memory(value, owners);
91
+ const def = T._structDef ?? T._unionDef ?? T;
92
+ const size = def.size;
93
+ if (!ArrayBuffer.isView(bytes) || bytes.byteLength < size) return bytes; // Validated by the addon.
94
+ // CPython's StructUnionType_paramfunc copies only above sizeof(void*).
95
+ if (size > pointerSize) {
96
+ const copy = snapshotArgumentBytes(bytes, def);
97
+ retainArgument(owners, copy);
98
+ return copy;
99
+ }
100
+ if (mirrorsActive && isMirror(bytes)) {
101
+ // Another alias can write native memory during a later from_param.
102
+ // Read it when the addon marshals the argument, not during JS conversion.
103
+ return {
104
+ get _buffer() {
105
+ refresh(bytes, 0, size);
106
+ return bytes;
107
+ },
108
+ };
109
+ }
110
+ return bytes;
111
+ };
112
+ const build = factory === undefined ? (values, owners) => coerce(instance(values), owners) : (values, owners) => factory(values, coerce, owners);
113
+ const convert = (a, owners, adapted = false) => {
263
114
  // A plain object of field values, the common case, skips the generic
264
115
  // parameter probes: only `_as_parameter_` and `_buffer` change its meaning.
265
116
  // Their presence is tested without reading them, so an adapter getter runs
@@ -268,35 +119,25 @@ function structArgument(T, index) {
268
119
  retainArgument(owners, a);
269
120
  return build(a, owners);
270
121
  }
271
- a = resolveArgument(a, owners, index);
122
+ a = resolveArgument(a, owners, index, adapted ? undefined : declaredClass);
272
123
  retainArgument(owners, a);
273
124
  if (Array.isArray(a)) {
274
125
  // Python rifiuta anche una tupla.
275
126
  throw new ArgumentError(`argument ${index + 1}: TypeError: expected ${T.name || "structure"} instance instead of Array`);
276
127
  }
277
128
  if (a !== null && typeof a === "object" && a._buffer === undefined && a._as_parameter_ === undefined && !ArrayBuffer.isView(a) && !(a instanceof ArrayBuffer)) {
278
- return coerce(instance(a), owners);
129
+ return build(a, owners);
279
130
  }
280
131
  return coerce(a, owners);
281
132
  };
282
133
  // A plain object of field values becomes a fresh Buffer passed directly to
283
134
  // the call, so nothing else needs to stay reachable.
284
135
  convert.needsOwners = (a) => needsArgumentOwners(a) && !(Object.getPrototypeOf(a) === Object.prototype && !("_buffer" in a) && !("_as_parameter_" in a));
136
+ // A user from_param has already accepted the argument; marshal its result.
137
+ if (declaredClass !== undefined) Object.defineProperty(convert, "marshalAdapted", { value: (a, owners) => convert(a, owners, true) });
285
138
  return convert;
286
139
  }
287
140
 
288
- /**
289
- * Python default conversion (no argtypes, variadic arguments): a SimpleCData
290
- * instance is passed by value (`abs(c_int(-5))`), other objects as
291
- * {@link coerceObject}.
292
- */
293
- export function coerceValue(a, owners) {
294
- if (a === null || (typeof a !== "object" && typeof a !== "function")) return a;
295
- retainArgument(owners, a);
296
- if (a._isSimpleCDataInstance === true) return a.value;
297
- return coerceObject(a, owners);
298
- }
299
-
300
141
  /**
301
142
  * Conversion of an argument beyond `argtypes` (variadic, or without
302
143
  * argtypes): a numeric SimpleCData instance keeps its type and snapshots its
@@ -315,6 +156,19 @@ export function coerceVariadic(a, owners) {
315
156
  return coerceObject(a, owners);
316
157
  }
317
158
 
159
+ function declaredArgument(t, index, native) {
160
+ if (isStructType(t)) return structArgument(t, index, native.POINTER_SIZE);
161
+ if (t !== null && (typeof t === "function" || typeof t === "object") && t._isArrayType === true) return arrayArgument(t, index);
162
+ if (t !== null && typeof t === "object" && t._pointerTo !== undefined) return pointerArgument(t, index, native);
163
+ const kind = typeof t === "function" ? t._type : t;
164
+ if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
165
+ if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
166
+ if (typeof t === "function" && t._isSimpleCData === true) return scalarArgument(t, kind, index, native);
167
+ // A scalar CType number as argtype: the same conversion order.
168
+ const check = typeof kind === "number" ? scalarCheck(kind, index, native) : undefined;
169
+ return check === undefined ? coerceObject : (a, owners) => check(coerceObject(a, owners));
170
+ }
171
+
318
172
  /**
319
173
  * Argument converters for `argtypes`, one per position. A SimpleCData instance
320
174
  * passed to a simple-type parameter is its value; to a pointer-like parameter
@@ -326,34 +180,26 @@ export function coerceVariadic(a, owners) {
326
180
  * @returns {Function[]} One converter per declared argument
327
181
  */
328
182
  export function argumentConverters(argTypes, native) {
329
- const baseConverter = (t, index) => {
330
- if (isStructType(t)) return structArgument(t, index);
331
- if (t !== null && (typeof t === "function" || typeof t === "object") && t._isArrayType === true) return arrayArgument(t, index);
332
- if (t !== null && typeof t === "object" && t._pointerTo !== undefined) return pointerArgument(t, index, native);
333
- const kind = typeof t === "function" ? t._type : t;
334
- if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
335
- if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
336
- if (typeof t !== "function" || t._isSimpleCData !== true) {
337
- // A scalar CType number as argtype: the same conversion order.
338
- const check = typeof kind === "number" ? scalarCheck(kind, index, native) : undefined;
339
- return check === undefined ? coerceObject : (a, owners) => check(coerceObject(a, owners));
340
- }
341
- return scalarArgument(t, kind, index, native);
342
- };
343
- const converters = argTypes.map((t, index) => {
344
- const base = baseConverter(t, index);
183
+ return argTypes.map((t, index) => {
184
+ const base = declaredArgument(t, index, native);
345
185
  if (t === null || (typeof t !== "function" && typeof t !== "object")) return base;
346
186
  const fromParam = t.from_param;
347
- if (fromParam === undefined) return base;
348
- return fromParamArgument(t, base.fromParam ?? base, index, fromParam);
187
+ if (fromParam === undefined) {
188
+ if (typeof t === "object" && base === coerceObject) requireDescriptor(t, native, index);
189
+ return base;
190
+ }
191
+ return fromParamArgument(t, base.marshalAdapted ?? base, index, fromParam);
349
192
  });
350
- return converters;
193
+ }
194
+
195
+ function readPointerBits(size, buffer) {
196
+ return size === 8 ? buffer.readBigUInt64LE(0) : BigInt(buffer.readUInt32LE(0));
351
197
  }
352
198
 
353
199
  function pointerValue(value, native) {
354
200
  const buffer = value._buffer;
355
201
  if (mirrorsActive) refresh(buffer);
356
- return native.POINTER_SIZE === 8 ? buffer.readBigUInt64LE(0) : BigInt(buffer.readUInt32LE(0));
202
+ return readPointerBits(native.POINTER_SIZE, buffer);
357
203
  }
358
204
 
359
205
  function voidPointerArgument(index, native) {
@@ -396,7 +242,7 @@ function stringArgument(T, kind, index, native) {
396
242
  fail(value);
397
243
  };
398
244
  // A custom from_param result is already adapted and may be a c_void_p.
399
- Object.defineProperty(convert, "fromParam", {
245
+ Object.defineProperty(convert, "marshalAdapted", {
400
246
  value: (value, owners) => {
401
247
  value = resolveArgument(value, owners, index);
402
248
  if (value?._isSimpleCDataInstance === true) {
@@ -505,15 +351,15 @@ function scalarArgument(T, kind, index, native) {
505
351
  return checked(objectMemory(value, owners));
506
352
  };
507
353
  const convert = make(false);
508
- Object.defineProperty(convert, "fromParam", { value: make(true) });
354
+ Object.defineProperty(convert, "marshalAdapted", { value: make(true) });
509
355
  // A valid primitive value (not an object or a function) is returned unchanged.
510
356
  Object.defineProperty(convert, "passesPrimitives", { value: true });
511
357
  return convert;
512
358
  }
513
359
 
514
- function resolveArgument(value, owners, index) {
360
+ function resolveArgument(value, owners, index, expectedStruct) {
515
361
  try {
516
- return resolveParameter(value, owners);
362
+ return resolveParameter(value, owners, expectedStruct);
517
363
  } catch (error) {
518
364
  throw new ArgumentError(`argument ${index + 1}: ${error?.name ?? "Error"}: ${error?.message ?? String(error)}`, { cause: error });
519
365
  }
@@ -565,8 +411,9 @@ function pointerArgument(T, index, native) {
565
411
  if (typeof base === "function" && value instanceof base) return objectMemory(value, owners);
566
412
  const kind = value.constructor?._type;
567
413
  if ((base._charKind === "char" && kind === native.CType.STRING) || (base._charKind === "wchar" && kind === native.CType.WSTRING)) {
414
+ // Unlike pointerValue, this path reads _buffer again after refreshing a mirror. A getter can observe both reads.
568
415
  if (mirrorsActive) refresh(value._buffer);
569
- return native.POINTER_SIZE === 8 ? value._buffer.readBigUInt64LE(0) : BigInt(value._buffer.readUInt32LE(0));
416
+ return readPointerBits(native.POINTER_SIZE, value._buffer);
570
417
  }
571
418
  fail();
572
419
  }
@@ -654,188 +501,3 @@ export function convertArguments(args, converters, owners) {
654
501
  }
655
502
  return out;
656
503
  }
657
-
658
- function copyResultBytes(result) {
659
- const bytes = Buffer.alloc(result.length);
660
- bytes.set(result);
661
- return bytes;
662
- }
663
-
664
- /**
665
- * Python restype conversion done in JS: `POINTER(T)` returns a pointer object
666
- * (`null` for NULL), a CFUNCTYPE type returns a callable. Undefined when the
667
- * native result is already final.
668
- *
669
- * @param {*} restype - Declared return type
670
- * @returns {Function|undefined} Converter from the native result
671
- */
672
- export function resultConverter(restype) {
673
- if (isScalarSubclass(restype)) return (bytes) => scalarView(restype, bytes);
674
- if (restype?._isVariantBool === true) return (result) => result !== 0;
675
- if (restype !== null && typeof restype === "object" && restype._pointerTo !== undefined) {
676
- return (r) => (r === null || r === 0n ? null : restype.fromAddress(r));
677
- }
678
- if (typeof restype === "function" && restype._isFuncPtr === true) {
679
- return (r) => (r === null || r === 0n ? null : restype(r));
680
- }
681
- // Snapshot before constructors/readers can reenter: toObject may keep
682
- // array views or union getters over the native function's reusable buffer.
683
- if (typeof restype === "function" && typeof restype._buildStruct === "function") {
684
- return (r) => new restype(copyResultBytes(r));
685
- }
686
- if (restype !== null && typeof restype === "object" && restype._isStructType === true) {
687
- return structResultReaders.get(restype) ?? ((r) => restype.toObject(copyResultBytes(r)));
688
- }
689
- return undefined;
690
- }
691
-
692
- export function scalarResult(restype) {
693
- return isScalarSubclass(restype);
694
- }
695
-
696
- export function resultCheck(restype, name, loader = "FFI") {
697
- const check = restype?._check_retval_;
698
- const hresult = restype?._isHResult === true;
699
- if (!hresult && check === undefined) return undefined;
700
- return (result) => {
701
- if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
702
- if (hresult) {
703
- const value = result?._isSimpleCDataInstance === true ? result.value : result;
704
- const number = typeof value === "bigint" ? Number(value) : value;
705
- if (typeof number === "number" && number < 0) {
706
- const hex = (number >>> 0).toString(16).padStart(8, "0").toUpperCase();
707
- const error = new Error(`${loader} '${name}' failed with HRESULT 0x${hex}`);
708
- error.hresult = number;
709
- error.winerror = number >>> 0;
710
- throw error;
711
- }
712
- }
713
- return check === undefined ? result : check.call(restype, result);
714
- };
715
- }
716
-
717
- /**
718
- * True when `restype` is a struct or union returned by value: the native
719
- * function must then return its bytes (FFIFunction option `struct_buffer`),
720
- * which {@link resultConverter} turns into the result.
721
- *
722
- * @param {*} restype - Declared return type
723
- * @returns {boolean}
724
- */
725
- export function structResult(restype) {
726
- return (typeof restype === "function" && typeof restype._buildStruct === "function") || (restype !== null && typeof restype === "object" && restype._isStructType === true);
727
- }
728
-
729
- /**
730
- * Adapt a JS function used as a C callback to Python semantics: arguments
731
- * declared `POINTER(T)` are passed as pointer objects (`null` for NULL), and an
732
- * object returned by the function (pointer, SimpleCData instance, ...) is
733
- * converted like an argument.
734
- *
735
- * @param {Function} fn - JS callback
736
- * @param {Array} argTypes - Declared argument types
737
- * @returns {Function} Function to register with the native callback
738
- */
739
- export function adaptCallbackFunction(fn, argTypes, returnType, native) {
740
- const scalarTypes = argTypes.map((type) => (isScalarSubclass(type) ? type : null));
741
- const hasScalars = scalarTypes.some((type) => type !== null);
742
- const pointerTypes = argTypes.map((t) => (t !== null && typeof t === "object" && t._pointerTo !== undefined ? t : null));
743
- const hasPointers = pointerTypes.some((t) => t !== null);
744
- // Struct/union per valore: il nativo passa una copia in un Buffer.
745
- const structViews = argTypes.map(structView);
746
- const hasStructs = structViews.some((view) => view !== null);
747
- const variantArgs = argTypes.map((type) => type?._isVariantBool === true);
748
- const hasVariants = variantArgs.some(Boolean);
749
- const variantResult = returnType?._isVariantBool === true;
750
- const toResult = stringResult(returnType, native);
751
- const convertResult = (result) => {
752
- if (variantResult) return returnType.from_param(result);
753
- if (toResult !== undefined && typeof result === "string") return toResult(result);
754
- return result !== null && (typeof result === "object" || typeof result === "function") ? coerceValue(result) : result;
755
- };
756
- if (!hasScalars && !hasVariants && !hasPointers && !hasStructs) {
757
- // The native trampoline passes exactly argTypes.length values with an
758
- // undefined receiver. Like CPython (tp_call), the handler is invoked
759
- // directly: own `call`/`apply` properties are not consulted.
760
- switch (argTypes.length) {
761
- case 0:
762
- return () => convertResult(fn());
763
- case 1:
764
- return (a0) => convertResult(fn(a0));
765
- case 2:
766
- return (a0, a1) => convertResult(fn(a0, a1));
767
- case 3:
768
- return (a0, a1, a2) => convertResult(fn(a0, a1, a2));
769
- default:
770
- return (...args) => convertResult(reflectApply(fn, undefined, args));
771
- }
772
- }
773
- return (...args) => {
774
- if (hasScalars) {
775
- for (let i = 0; i < scalarTypes.length; i++) {
776
- if (scalarTypes[i] !== null) args[i] = scalarView(scalarTypes[i], args[i]);
777
- }
778
- }
779
- if (hasVariants) {
780
- for (let i = 0; i < variantArgs.length; i++) {
781
- if (variantArgs[i] && scalarTypes[i] === null) args[i] = args[i] !== 0;
782
- }
783
- }
784
- if (hasPointers) {
785
- for (let i = 0; i < pointerTypes.length; i++) {
786
- const T = pointerTypes[i];
787
- if (T !== null && args[i] !== null) {
788
- args[i] = T.fromAddress(args[i]);
789
- }
790
- }
791
- }
792
- if (hasStructs) {
793
- for (let i = 0; i < structViews.length; i++) {
794
- if (structViews[i] !== null) args[i] = structViews[i](args[i]);
795
- }
796
- }
797
- return convertResult(reflectApply(fn, undefined, args));
798
- };
799
- }
800
-
801
- /**
802
- * View of a struct/union argument of a callback (Buffer with a copy of the
803
- * C value): an instance of the class, or of the struct()/union() definition.
804
- *
805
- * @returns {Function|null} Converter, null for other argument types
806
- */
807
- function structView(type) {
808
- if (typeof type === "function" && typeof type._buildStruct === "function") return (buf) => new type(buf);
809
- if (type !== null && typeof type === "object" && type._isStructType === true) {
810
- let handler;
811
- return (buf) => {
812
- handler ??= buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true });
813
- return new Proxy(buf, handler);
814
- };
815
- }
816
- return null;
817
- }
818
-
819
- /**
820
- * Result of a callback whose restype is c_char_p / c_wchar_p and that returns
821
- * a JS string: a NUL-terminated buffer, kept alive as long as the callback
822
- * (Python keeps it forever, with "RuntimeWarning: memory leak in callback
823
- * function"). Buffers are cached by value, so a callback that returns the
824
- * same strings does not accumulate memory.
825
- *
826
- * @returns {Function|undefined} Converter, undefined for other restypes
827
- */
828
- function stringResult(returnType, native) {
829
- if (native === undefined || typeof returnType !== "function" || returnType._isSimpleCData !== true) return undefined;
830
- const wide = returnType._type === native.CType.WSTRING;
831
- if (!wide && returnType._type !== native.CType.STRING) return undefined;
832
- const kept = new Map();
833
- return (value) => {
834
- let buf = kept.get(value);
835
- if (buf === undefined) {
836
- buf = wide ? Buffer.concat([encodeWide(value, native.WCHAR_SIZE), Buffer.alloc(native.WCHAR_SIZE)]) : Buffer.from(`${value}\0`, "utf8");
837
- kept.set(value, buf);
838
- }
839
- return buf;
840
- };
841
- }