node-ctypes 2.2.0 → 2.4.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 (38) hide show
  1. package/CHANGELOG.md +932 -0
  2. package/README.md +504 -99
  3. package/build/Release/ctypes-darwin-arm64.node +0 -0
  4. package/build/Release/ctypes-darwin-x64.node +0 -0
  5. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  6. package/build/Release/ctypes-linux-arm64.node +0 -0
  7. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  8. package/build/Release/ctypes-linux-x64.node +0 -0
  9. package/build/Release/ctypes-win32-arm64.node +0 -0
  10. package/build/Release/ctypes-win32-x64.node +0 -0
  11. package/lib/core/Library.js +136 -109
  12. package/lib/core/callback.js +17 -20
  13. package/lib/core/conversions.js +376 -16
  14. package/lib/core/funcptr.js +148 -73
  15. package/lib/core/lazy-loader.js +10 -4
  16. package/lib/core/types.js +201 -98
  17. package/lib/index.d.ts +276 -83
  18. package/lib/index.js +44 -32
  19. package/lib/memory/buffer.js +82 -22
  20. package/lib/memory/operations.js +55 -45
  21. package/lib/memory/pointer.js +233 -57
  22. package/lib/platform/constants.js +0 -1
  23. package/lib/platform/errors.js +48 -4
  24. package/lib/platform/find_library.js +78 -19
  25. package/lib/platform/win_types.js +8 -3
  26. package/lib/structures/Structure.js +252 -203
  27. package/lib/structures/Union.js +10 -21
  28. package/lib/structures/helpers/array.js +102 -16
  29. package/lib/structures/helpers/bitfield.js +75 -150
  30. package/lib/structures/helpers/common.js +310 -21
  31. package/lib/structures/helpers/layout.js +145 -0
  32. package/lib/structures/helpers/struct.js +160 -419
  33. package/lib/structures/helpers/union.js +154 -155
  34. package/lib/structures/helpers/wrap.js +3 -15
  35. package/lib/types/SimpleCData.js +11 -32
  36. package/lib/types/primitives.js +160 -113
  37. package/lib/utils/cache.js +34 -2
  38. package/package.json +4 -1
@@ -7,6 +7,56 @@
7
7
  */
8
8
 
9
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
+ import { byrefOwners, isScalarSubclass, resolveParameter, scalarView } from "../structures/helpers/common.js";
14
+
15
+ const activeArgumentOwners = new Set();
16
+
17
+ function retainArgument(owners, value) {
18
+ if (owners !== undefined && value !== null && (typeof value === "object" || typeof value === "function")) owners.push(value);
19
+ }
20
+
21
+ export function needsArgumentOwners(value) {
22
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return false;
23
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
24
+ return "_buffer" in value || "_as_parameter_" in value || (mirrorsActive && mirrorAddress(value) !== undefined);
25
+ }
26
+ return true;
27
+ }
28
+
29
+ export function argumentsNeedOwners(args) {
30
+ for (let i = 0; i < args.length; i++) if (needsArgumentOwners(args[i])) return true;
31
+ return false;
32
+ }
33
+
34
+ // The registry is a GC root, including while another converter reenters JS.
35
+ export function callWithArgumentOwners(ffiFunc, method, args, converters, finish, resultHandler, checkedCall) {
36
+ const owners = [];
37
+ activeArgumentOwners.add(owners);
38
+ let pending = false;
39
+ try {
40
+ const converted = convertArguments(args, converters, owners);
41
+ const result =
42
+ resultHandler === undefined ? ffiFunc[method](...converted) : checkedCall === undefined ? ffiFunc[method === "callAsync" ? "_callAsyncWithErrcheck" : "_callWithErrcheck"](resultHandler, ...converted) : checkedCall(resultHandler, ...converted);
43
+ if (method === "callAsync") {
44
+ const completed = finish === undefined ? result : result.then((value) => finish(value, args));
45
+ const promise = completed.finally(() => activeArgumentOwners.delete(owners));
46
+ pending = true;
47
+ return promise;
48
+ }
49
+ return finish === undefined ? result : finish(result, args);
50
+ } finally {
51
+ if (!pending) activeArgumentOwners.delete(owners);
52
+ }
53
+ }
54
+
55
+ export function callWithResultHandler(ffiFunc, method, args, converters, handler, retainOwners, checkedCall) {
56
+ if (retainOwners) return callWithArgumentOwners(ffiFunc, method, args, converters, undefined, handler, checkedCall);
57
+ if (checkedCall !== undefined) return checkedCall(handler, ...convertArguments(args, converters));
58
+ return ffiFunc[method === "callAsync" ? "_callAsyncWithErrcheck" : "_callWithErrcheck"](handler, ...convertArguments(args, converters));
59
+ }
10
60
 
11
61
  /**
12
62
  * Base conversion of an object argument:
@@ -17,45 +67,93 @@ import { mirrorAddress, mirrorsActive, refresh } from "../memory/mirror.js";
17
67
  * original address
18
68
  * - anything else unchanged
19
69
  */
20
- export function coerceObject(a) {
70
+ export function coerceObject(a, owners) {
71
+ return objectMemory(resolveParameter(a, owners), owners);
72
+ }
73
+
74
+ function objectMemory(a, owners) {
21
75
  if (a === null || typeof a !== "object") return a;
76
+ retainArgument(owners, a);
22
77
  const b = a._buffer;
23
78
  if (b !== undefined) {
79
+ retainArgument(owners, b);
24
80
  // Puntatore creato da indirizzo (fromAddress): senza Buffer va passato
25
81
  // l'indirizzo, altrimenti al C arriverebbe NULL.
26
82
  if (b === null && a._pointerType !== undefined) return a.address;
27
83
  if (mirrorsActive) return mirrorAddress(b) ?? b;
28
84
  return b;
29
85
  }
30
- if (a._as_parameter_ !== undefined) return a._as_parameter_;
86
+ const parameter = a._as_parameter_;
87
+ if (parameter !== undefined) {
88
+ retainArgument(owners, parameter);
89
+ return parameter;
90
+ }
31
91
  if (mirrorsActive) return mirrorAddress(a) ?? a;
32
92
  return a;
33
93
  }
34
94
 
35
95
  // Struct/union passato per valore: il nativo copia i byte del Buffer, che per
36
96
  // una copia di memoria nativa vanno prima riletti.
37
- function coerceStructValue(a) {
97
+ function coerceStructValue(a, owners) {
38
98
  if (a !== null && typeof a === "object") {
99
+ retainArgument(owners, a);
39
100
  const b = Buffer.isBuffer(a._buffer) ? a._buffer : a;
40
101
  if (Buffer.isBuffer(b)) {
102
+ retainArgument(owners, b);
41
103
  refresh(b);
42
104
  return b;
43
105
  }
44
106
  }
45
- return coerceObject(a);
107
+ return coerceObject(a, owners);
46
108
  }
47
109
 
48
110
  const isStructType = (t) => t !== null && (typeof t === "function" || typeof t === "object") && (typeof t._buildStruct === "function" || typeof t._buildUnion === "function" || t._isStructType === true);
49
111
 
112
+ /**
113
+ * Converter for a struct/union passed by value. A plain object (fields by
114
+ * name, a node-ctypes extension) becomes an instance of the type first, so
115
+ * bit fields and fields of `_pack_` layouts (which the native description
116
+ * holds as bytes) get their values. An array is rejected, as a Python tuple.
117
+ */
118
+ function structArgument(T, index) {
119
+ const instance = typeof T === "function" ? (values) => new T(values) : (values) => T.create(values);
120
+ const coerce = mirrorsActive ? coerceStructValue : coerceObject;
121
+ return (a, owners) => {
122
+ a = resolveArgument(a, owners, index);
123
+ retainArgument(owners, a);
124
+ if (Array.isArray(a)) {
125
+ // Python rifiuta anche una tupla.
126
+ throw new ArgumentError(`argument ${index + 1}: TypeError: expected ${T.name || "structure"} instance instead of Array`);
127
+ }
128
+ if (a !== null && typeof a === "object" && a._buffer === undefined && a._as_parameter_ === undefined && !ArrayBuffer.isView(a) && !(a instanceof ArrayBuffer)) {
129
+ return coerce(instance(a), owners);
130
+ }
131
+ return coerce(a, owners);
132
+ };
133
+ }
134
+
50
135
  /**
51
136
  * Python default conversion (no argtypes, variadic arguments): a SimpleCData
52
137
  * instance is passed by value (`abs(c_int(-5))`), other objects as
53
138
  * {@link coerceObject}.
54
139
  */
55
- export function coerceValue(a) {
56
- if (a === null || typeof a !== "object") return a;
140
+ export function coerceValue(a, owners) {
141
+ if (a === null || (typeof a !== "object" && typeof a !== "function")) return a;
142
+ retainArgument(owners, a);
57
143
  if (a._isSimpleCDataInstance === true) return a.value;
58
- return coerceObject(a);
144
+ return coerceObject(a, owners);
145
+ }
146
+
147
+ /**
148
+ * Conversion of an argument beyond `argtypes` (variadic, or without
149
+ * argtypes): a SimpleCData instance is passed as is, and the native call uses
150
+ * its type, as Python does (`printf("%f", c_double(2.0))`).
151
+ */
152
+ export function coerceVariadic(a, owners) {
153
+ a = resolveParameter(a, owners);
154
+ retainArgument(owners, a);
155
+ if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return a;
156
+ return coerceObject(a, owners);
59
157
  }
60
158
 
61
159
  /**
@@ -70,32 +168,183 @@ export function coerceValue(a) {
70
168
  */
71
169
  export function argumentConverters(argTypes, native) {
72
170
  const pointerKinds = new Set([native.CType.POINTER, native.CType.STRING, native.CType.WSTRING]);
73
- return argTypes.map((t) => {
74
- if (mirrorsActive && isStructType(t)) return coerceStructValue;
171
+ const baseConverter = (t, index) => {
172
+ if (isStructType(t)) return structArgument(t, index);
173
+ if (t !== null && (typeof t === "function" || typeof t === "object") && t._isArrayType === true) return arrayArgument(t, index);
174
+ if (t !== null && typeof t === "object" && t._pointerTo !== undefined) return pointerArgument(t, index, native);
75
175
  if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
76
- if (!pointerKinds.has(t._type)) return coerceValue;
77
- return (a) => {
176
+ if (!pointerKinds.has(t._type)) return scalarArgument(t, index);
177
+ return (a, owners) => {
178
+ a = resolveArgument(a, owners, index);
78
179
  if (a === null || typeof a !== "object") return a;
180
+ retainArgument(owners, a);
79
181
  if (a._isSimpleCDataInstance === true && a instanceof t) return a.value;
80
- return coerceObject(a);
182
+ return coerceObject(a, owners);
81
183
  };
184
+ };
185
+ return argTypes.map((t, index) => {
186
+ const base = baseConverter(t, index);
187
+ if (t === null || (typeof t !== "function" && typeof t !== "object") || typeof t.from_param !== "function") return base;
188
+ return fromParamArgument(t, base, index);
82
189
  });
83
190
  }
84
191
 
192
+ function scalarArgument(T, index) {
193
+ const boolean = T._isBoolean === true;
194
+ return (value, owners) => {
195
+ if (value !== null && (typeof value === "object" || typeof value === "function")) value = resolveArgument(value, owners, index);
196
+ if (value === null || typeof value !== "object") return value;
197
+ retainArgument(owners, value);
198
+ if (value._isSimpleCDataInstance === true) {
199
+ if (!boolean && !(value instanceof T)) {
200
+ throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible types, ${value.constructor.name} instance instead of ${T.name} instance`);
201
+ }
202
+ return value.value;
203
+ }
204
+ return objectMemory(value, owners);
205
+ };
206
+ }
207
+
208
+ function resolveArgument(value, owners, index) {
209
+ try {
210
+ return resolveParameter(value, owners);
211
+ } catch (error) {
212
+ throw new ArgumentError(`argument ${index + 1}: ${error?.name ?? "Error"}: ${error?.message ?? String(error)}`, { cause: error });
213
+ }
214
+ }
215
+
216
+ const compatibleType = (actual, expected) => actual === expected || (typeof actual === "function" && typeof expected === "function" && actual.prototype instanceof expected);
217
+
218
+ function pointerArgument(T, index, native) {
219
+ const base = T._pointerTo;
220
+ const fail = () => {
221
+ throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible pointer, expected POINTER(${base.name ?? "type"})`);
222
+ };
223
+ const convert = (value, owners) => {
224
+ value = resolveArgument(value, owners, index);
225
+ if (value === null || value === undefined || typeof value === "bigint") return value;
226
+ if (typeof value === "number") {
227
+ if (!Number.isInteger(value)) fail();
228
+ return value;
229
+ }
230
+ if (typeof value === "string" && base._charKind === "char") return value;
231
+ if (typeof value === "string" && base._charKind === "wchar") {
232
+ const buffer = Buffer.concat([encodeWide(value, native.WCHAR_SIZE), Buffer.alloc(native.WCHAR_SIZE)]);
233
+ retainArgument(owners, buffer);
234
+ return buffer;
235
+ }
236
+ if (typeof base === "function" && value instanceof base) return objectMemory(value, owners);
237
+ const reference = value !== null && (typeof value === "object" || typeof value === "function") ? byrefOwners.get(value) : undefined;
238
+ if (reference !== undefined) {
239
+ if (reference.type !== undefined && !compatibleType(reference.type, base)) fail();
240
+ return objectMemory(value, owners);
241
+ }
242
+ if (value?._pointerType !== undefined) {
243
+ if (!compatibleType(value._pointerType._pointerTo, base)) fail();
244
+ return objectMemory(value, owners);
245
+ }
246
+ if (value?._arrayType !== undefined) {
247
+ if ((!compatibleType(value._arrayType, base) && !compatibleType(value._arrayType.elementType, base)) || value._arrayType._swapped_) fail();
248
+ return coerceObject(value, owners);
249
+ }
250
+ if (value?._isSimpleCDataInstance === true || value?._structDef !== undefined) {
251
+ if (typeof base === "function" && value instanceof base) return objectMemory(value, owners);
252
+ const kind = value.constructor?._type;
253
+ if ((base._charKind === "char" && kind === native.CType.STRING) || (base._charKind === "wchar" && kind === native.CType.WSTRING)) {
254
+ if (mirrorsActive) refresh(value._buffer);
255
+ return native.POINTER_SIZE === 8 ? value._buffer.readBigUInt64LE(0) : BigInt(value._buffer.readUInt32LE(0));
256
+ }
257
+ fail();
258
+ }
259
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || Buffer.isBuffer(value?._buffer)) return objectMemory(value, owners);
260
+ fail();
261
+ };
262
+ if (base._charKind === "wchar") Object.defineProperty(convert, "requiresOwners", { value: true });
263
+ return convert;
264
+ }
265
+
266
+ /**
267
+ * Converter for an argtype with a `from_param` method (Python protocol): it
268
+ * receives the argument as passed, its result (or the result's
269
+ * `_as_parameter_`) is converted as the declared type. Its errors become
270
+ * ArgumentError "argument N: <name>: <message>", as in Python.
271
+ */
272
+ function fromParamArgument(T, base, index) {
273
+ const converter = (a, owners) => {
274
+ retainArgument(owners, a);
275
+ let converted;
276
+ try {
277
+ converted = T.from_param(a);
278
+ } catch (e) {
279
+ if (e instanceof ArgumentError) throw e;
280
+ throw new ArgumentError(`argument ${index + 1}: ${e?.name ?? "Error"}: ${e?.message ?? String(e)}`, { cause: e });
281
+ }
282
+ retainArgument(owners, converted);
283
+ return base(converted, owners);
284
+ };
285
+ Object.defineProperty(converter, "requiresOwners", { value: true });
286
+ return converter;
287
+ }
288
+
289
+ const arrayTypeName = (T) => `${T.elementType?.name || "array"} * ${T.length}`;
290
+
291
+ function describeValue(a) {
292
+ if (a === null) return "null";
293
+ if (typeof a !== "object") return typeof a;
294
+ if (a._arrayType !== undefined) return arrayTypeName(a._arrayType);
295
+ return a.constructor?.name ?? "object";
296
+ }
297
+
298
+ /**
299
+ * Converter for an array parameter (`argtypes = [c_int * 4]`): the array is
300
+ * passed by address, as in C and Python. As Python, only instances of the
301
+ * same array type (element type and length) are accepted; Buffers and typed
302
+ * arrays are also accepted as memory.
303
+ *
304
+ * @param {Function} T - Array type
305
+ * @param {number} index - Parameter position (for the error message)
306
+ * @returns {Function} Converter
307
+ */
308
+ function arrayArgument(T, index) {
309
+ return (a, owners) => {
310
+ a = resolveArgument(a, owners, index);
311
+ retainArgument(owners, a);
312
+ if (a !== null && typeof a === "object") {
313
+ const arrayType = a._arrayType;
314
+ if (arrayType !== undefined) {
315
+ if (arrayType === T || (arrayType.elementType === T.elementType && arrayType.length === T.length)) return coerceObject(a, owners);
316
+ } else if (ArrayBuffer.isView(a) || a instanceof ArrayBuffer) {
317
+ return coerceObject(a, owners);
318
+ } else if (a._as_parameter_ !== undefined) {
319
+ const parameter = a._as_parameter_;
320
+ retainArgument(owners, parameter);
321
+ return parameter;
322
+ }
323
+ }
324
+ throw new ArgumentError(`argument ${index + 1}: TypeError: expected ${arrayTypeName(T)} instance instead of ${describeValue(a)}`);
325
+ };
326
+ }
327
+
85
328
  /**
86
329
  * Convert all call arguments: declared ones with their converter, the rest
87
330
  * (variadic or without argtypes) with the Python default conversion.
88
331
  */
89
- export function convertArguments(args, converters) {
332
+ export function convertArguments(args, converters, owners) {
90
333
  const n = args.length;
91
334
  const declared = converters.length;
92
335
  const out = new Array(n);
93
336
  for (let i = 0; i < n; i++) {
94
- out[i] = i < declared ? converters[i](args[i]) : coerceValue(args[i]);
337
+ out[i] = i < declared ? converters[i](args[i], owners) : coerceVariadic(args[i], owners);
95
338
  }
96
339
  return out;
97
340
  }
98
341
 
342
+ function copyResultBytes(result) {
343
+ const bytes = Buffer.alloc(result.length);
344
+ bytes.set(result);
345
+ return bytes;
346
+ }
347
+
99
348
  /**
100
349
  * Python restype conversion done in JS: `POINTER(T)` returns a pointer object
101
350
  * (`null` for NULL), a CFUNCTYPE type returns a callable. Undefined when the
@@ -105,15 +354,62 @@ export function convertArguments(args, converters) {
105
354
  * @returns {Function|undefined} Converter from the native result
106
355
  */
107
356
  export function resultConverter(restype) {
357
+ if (isScalarSubclass(restype)) return (bytes) => scalarView(restype, bytes);
358
+ if (restype?._isVariantBool === true) return (result) => result !== 0;
108
359
  if (restype !== null && typeof restype === "object" && restype._pointerTo !== undefined) {
109
360
  return (r) => (r === null || r === 0n ? null : restype.fromAddress(r));
110
361
  }
111
362
  if (typeof restype === "function" && restype._isFuncPtr === true) {
112
363
  return (r) => (r === null || r === 0n ? null : restype(r));
113
364
  }
365
+ // Snapshot before constructors/readers can reenter: toObject may keep
366
+ // array views or union getters over the native function's reusable buffer.
367
+ if (typeof restype === "function" && typeof restype._buildStruct === "function") {
368
+ return (r) => new restype(copyResultBytes(r));
369
+ }
370
+ if (restype !== null && typeof restype === "object" && restype._isStructType === true) {
371
+ return (r) => restype.toObject(copyResultBytes(r));
372
+ }
114
373
  return undefined;
115
374
  }
116
375
 
376
+ export function scalarResult(restype) {
377
+ return isScalarSubclass(restype);
378
+ }
379
+
380
+ export function resultCheck(restype, name, loader = "FFI") {
381
+ const check = restype?._check_retval_;
382
+ if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
383
+ const hresult = restype?._isHResult === true;
384
+ if (!hresult && check === undefined) return undefined;
385
+ return (result) => {
386
+ if (hresult) {
387
+ const value = result?._isSimpleCDataInstance === true ? result.value : result;
388
+ const number = typeof value === "bigint" ? Number(value) : value;
389
+ if (typeof number === "number" && number < 0) {
390
+ const hex = (number >>> 0).toString(16).padStart(8, "0").toUpperCase();
391
+ const error = new Error(`${loader} '${name}' failed with HRESULT 0x${hex}`);
392
+ error.hresult = number;
393
+ error.winerror = number >>> 0;
394
+ throw error;
395
+ }
396
+ }
397
+ return check === undefined ? result : check.call(restype, result);
398
+ };
399
+ }
400
+
401
+ /**
402
+ * True when `restype` is a struct or union returned by value: the native
403
+ * function must then return its bytes (FFIFunction option `struct_buffer`),
404
+ * which {@link resultConverter} turns into the result.
405
+ *
406
+ * @param {*} restype - Declared return type
407
+ * @returns {boolean}
408
+ */
409
+ export function structResult(restype) {
410
+ return (typeof restype === "function" && typeof restype._buildStruct === "function") || (restype !== null && typeof restype === "object" && restype._isStructType === true);
411
+ }
412
+
117
413
  /**
118
414
  * Adapt a JS function used as a C callback to Python semantics: arguments
119
415
  * declared `POINTER(T)` are passed as pointer objects (`null` for NULL), and an
@@ -124,10 +420,29 @@ export function resultConverter(restype) {
124
420
  * @param {Array} argTypes - Declared argument types
125
421
  * @returns {Function} Function to register with the native callback
126
422
  */
127
- export function adaptCallbackFunction(fn, argTypes) {
423
+ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
424
+ const scalarTypes = argTypes.map((type) => (isScalarSubclass(type) ? type : null));
425
+ const hasScalars = scalarTypes.some((type) => type !== null);
128
426
  const pointerTypes = argTypes.map((t) => (t !== null && typeof t === "object" && t._pointerTo !== undefined ? t : null));
129
427
  const hasPointers = pointerTypes.some((t) => t !== null);
428
+ // Struct/union per valore: il nativo passa una copia in un Buffer.
429
+ const structViews = argTypes.map(structView);
430
+ const hasStructs = structViews.some((view) => view !== null);
431
+ const variantArgs = argTypes.map((type) => type?._isVariantBool === true);
432
+ const hasVariants = variantArgs.some(Boolean);
433
+ const variantResult = returnType?._isVariantBool === true;
434
+ const toResult = stringResult(returnType, native);
130
435
  return function (...args) {
436
+ if (hasScalars) {
437
+ for (let i = 0; i < scalarTypes.length; i++) {
438
+ if (scalarTypes[i] !== null) args[i] = scalarView(scalarTypes[i], args[i]);
439
+ }
440
+ }
441
+ if (hasVariants) {
442
+ for (let i = 0; i < variantArgs.length; i++) {
443
+ if (variantArgs[i] && scalarTypes[i] === null) args[i] = args[i] !== 0;
444
+ }
445
+ }
131
446
  if (hasPointers) {
132
447
  for (let i = 0; i < pointerTypes.length; i++) {
133
448
  const T = pointerTypes[i];
@@ -136,7 +451,52 @@ export function adaptCallbackFunction(fn, argTypes) {
136
451
  }
137
452
  }
138
453
  }
454
+ if (hasStructs) {
455
+ for (let i = 0; i < structViews.length; i++) {
456
+ if (structViews[i] !== null) args[i] = structViews[i](args[i]);
457
+ }
458
+ }
139
459
  const result = fn.apply(this, args);
140
- return result !== null && typeof result === "object" ? coerceValue(result) : result;
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;
463
+ };
464
+ }
465
+
466
+ /**
467
+ * View of a struct/union argument of a callback (Buffer with a copy of the
468
+ * C value): an instance of the class, or of the struct()/union() definition.
469
+ *
470
+ * @returns {Function|null} Converter, null for other argument types
471
+ */
472
+ function structView(type) {
473
+ if (typeof type === "function" && typeof type._buildStruct === "function") return (buf) => new type(buf);
474
+ if (type !== null && typeof type === "object" && type._isStructType === true) {
475
+ return (buf) => new Proxy(buf, buildWrapper(type, { instanceTag: "StructInstance", exposeAnonymous: true }));
476
+ }
477
+ return null;
478
+ }
479
+
480
+ /**
481
+ * Result of a callback whose restype is c_char_p / c_wchar_p and that returns
482
+ * a JS string: a NUL-terminated buffer, kept alive as long as the callback
483
+ * (Python keeps it forever, with "RuntimeWarning: memory leak in callback
484
+ * function"). Buffers are cached by value, so a callback that returns the
485
+ * same strings does not accumulate memory.
486
+ *
487
+ * @returns {Function|undefined} Converter, undefined for other restypes
488
+ */
489
+ function stringResult(returnType, native) {
490
+ if (native === undefined || typeof returnType !== "function" || returnType._isSimpleCData !== true) return undefined;
491
+ const wide = returnType._type === native.CType.WSTRING;
492
+ if (!wide && returnType._type !== native.CType.STRING) return undefined;
493
+ const kept = new Map();
494
+ return (value) => {
495
+ let buf = kept.get(value);
496
+ if (buf === undefined) {
497
+ buf = wide ? Buffer.concat([encodeWide(value, native.WCHAR_SIZE), Buffer.alloc(native.WCHAR_SIZE)]) : Buffer.from(`${value}\0`, "utf8");
498
+ kept.set(value, buf);
499
+ }
500
+ return buf;
141
501
  };
142
502
  }