node-ctypes 2.6.0 → 2.8.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 +56 -1
- package/README.md +6 -0
- 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 +3 -2
- package/lib/core/callback.js +3 -0
- package/lib/core/conversions.js +116 -32
- package/lib/index.d.ts +1 -1
- package/lib/memory/buffer.js +24 -0
- package/lib/structures/helpers/common.js +79 -3
- package/lib/structures/helpers/struct.js +33 -2
- package/lib/types/SimpleCData.js +8 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.8.0] - 2026-11-04
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **Scalar argument marshalling**: read genuine non-pointer CData arguments from
|
|
15
|
+
their backing bytes instead of overridden `.value` getters. Snapshot each
|
|
16
|
+
scalar before converting later arguments, including calls without `argtypes`,
|
|
17
|
+
matching CPython's conversion order.
|
|
18
|
+
- **Scalar adapters**: accept `from_param` results whose native scalar kind
|
|
19
|
+
matches the declared type, even when the CData instance belongs to a different
|
|
20
|
+
JavaScript class.
|
|
21
|
+
- **Examples navigation**: use explicit Electron and Cryptoki page titles
|
|
22
|
+
instead of duplicate `README` labels in the generated documentation.
|
|
23
|
+
|
|
24
|
+
### Performance
|
|
25
|
+
|
|
26
|
+
- **Cached library symbols**: reuse attribute-function wrappers with a single
|
|
27
|
+
cache lookup instead of separate `Map.has()` and `Map.get()` calls, preserving
|
|
28
|
+
wrapper identity, signature changes and lazy symbol resolution.
|
|
29
|
+
|
|
30
|
+
## [2.7.0] - 2026-11-03
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- **Callback dispatch**: `callback()` and `threadSafeCallback()` invoke the
|
|
35
|
+
JavaScript handler directly, like CPython's `tp_call`. Own `call` or `apply`
|
|
36
|
+
properties on the handler are no longer consulted. The receiver stays
|
|
37
|
+
`undefined` and the handler gets exactly the declared arguments.
|
|
38
|
+
- **Callback wrappers as arguments**: a `callback()` / `threadSafeCallback()`
|
|
39
|
+
wrapper passes its own code pointer even through an object derived with
|
|
40
|
+
`Object.create()` or a Proxy that redefines `_as_parameter_`. This matches
|
|
41
|
+
CPython and `CFUNCTYPE` instances.
|
|
42
|
+
|
|
43
|
+
### Performance
|
|
44
|
+
|
|
45
|
+
- **Native entry point**: `FFIFunction` calls use a raw Node-API callback that
|
|
46
|
+
reads up to eight arguments with one `napi_get_cb_info` and tries the simple
|
|
47
|
+
call path before building a `Napi::CallbackInfo`.
|
|
48
|
+
- **Structures by value**: plain-object arguments of scalar-only `struct()`
|
|
49
|
+
definitions are written by precompiled field writers into an off-heap
|
|
50
|
+
transient buffer. Structures up to 16 bytes use the simple call path. Scalar-only
|
|
51
|
+
results are read in place without a copy, unless `toObject` is overridden.
|
|
52
|
+
Measured `{x,y}` argument: about 1.3x Koffi, down from 4.3x. Return: about 0.9x,
|
|
53
|
+
down from 1.3x.
|
|
54
|
+
- **Argument owners**: synchronous calls keep conversion owners on a LIFO stack
|
|
55
|
+
instead of a `Set`. Calls with one to three owner-bearing arguments skip
|
|
56
|
+
intermediate arrays.
|
|
57
|
+
- **Callbacks**: wrappers are resolved through an internal brand. Handlers with
|
|
58
|
+
up to three arguments are called without a rest array. Numeric results are
|
|
59
|
+
converted with a single V8 read.
|
|
60
|
+
- **Variadic numbers**: classified and written to the argument slot with a
|
|
61
|
+
single read.
|
|
62
|
+
|
|
10
63
|
## [2.6.0] - 2026-10-30
|
|
11
64
|
|
|
12
65
|
### Added
|
|
@@ -1018,7 +1071,9 @@ It contains breaking changes: see [Migrating from 1.x](README.md#migrating-from-
|
|
|
1018
1071
|
|
|
1019
1072
|
Initial releases.
|
|
1020
1073
|
|
|
1021
|
-
[Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.
|
|
1074
|
+
[Unreleased]: https://github.com/dmazzella/node-ctypes/compare/v2.8.0...HEAD
|
|
1075
|
+
[2.8.0]: https://github.com/dmazzella/node-ctypes/compare/v2.7.0...v2.8.0
|
|
1076
|
+
[2.7.0]: https://github.com/dmazzella/node-ctypes/compare/v2.6.0...v2.7.0
|
|
1022
1077
|
[2.6.0]: https://github.com/dmazzella/node-ctypes/compare/v2.5.0...v2.6.0
|
|
1023
1078
|
[2.5.0]: https://github.com/dmazzella/node-ctypes/compare/v2.4.0...v2.5.0
|
|
1024
1079
|
[2.4.0]: https://github.com/dmazzella/node-ctypes/compare/v2.3.0...v2.4.0
|
package/README.md
CHANGED
|
@@ -631,6 +631,12 @@ As in Python, `from_param` receives the argument as passed (also with
|
|
|
631
631
|
`CFUNCTYPE` prototypes), its result is converted as the declared type, and
|
|
632
632
|
an error it throws becomes `ArgumentError` (`"argument 1: RangeError: ..."`).
|
|
633
633
|
|
|
634
|
+
Non-pointer scalar CData arguments are read from their backing bytes, not an
|
|
635
|
+
overridden public `.value` getter. Each value is snapshotted before converting
|
|
636
|
+
the next argument, even without `argtypes`. A scalar `from_param` converter may
|
|
637
|
+
return a CData instance of another class when its native scalar kind matches
|
|
638
|
+
the declared type.
|
|
639
|
+
|
|
634
640
|
Objects passed through argument adapters and the objects produced by their
|
|
635
641
|
conversions stay alive while later arguments are converted and until the
|
|
636
642
|
result and `errcheck` have been processed. With `callAsync()`, those temporary
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/lib/core/Library.js
CHANGED
|
@@ -179,8 +179,9 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
179
179
|
return Reflect.get(target, prop, receiver);
|
|
180
180
|
}
|
|
181
181
|
// Check if we already have a FunctionWrapper for this function name
|
|
182
|
-
|
|
183
|
-
|
|
182
|
+
const cached = target._funcWrapperCache.get(prop);
|
|
183
|
+
if (cached !== undefined) {
|
|
184
|
+
return cached;
|
|
184
185
|
}
|
|
185
186
|
// Create and cache a new FunctionWrapper
|
|
186
187
|
const wrapper = new FunctionWrapper(target, prop);
|
package/lib/core/callback.js
CHANGED
|
@@ -56,6 +56,7 @@
|
|
|
56
56
|
import { _toNativeReturnType, _toNativeTypes } from "./types.js";
|
|
57
57
|
import { adaptCallbackFunction, scalarResult } from "./conversions.js";
|
|
58
58
|
import { trackCallback } from "./callback-tracker.js";
|
|
59
|
+
import { callbackPointer } from "../structures/helpers/common.js";
|
|
59
60
|
|
|
60
61
|
function nativeContextHook(value, name, owners) {
|
|
61
62
|
if (value !== null && (typeof value === "object" || typeof value === "function")) {
|
|
@@ -196,6 +197,7 @@ export function callback(fn, returnType, argTypes = [], native, abi = undefined)
|
|
|
196
197
|
return cb.pointer;
|
|
197
198
|
},
|
|
198
199
|
});
|
|
200
|
+
Object.defineProperty(wrapper, callbackPointer, { value: cb.pointer });
|
|
199
201
|
return trackCallback(wrapper, fn, "callback");
|
|
200
202
|
}
|
|
201
203
|
|
|
@@ -357,5 +359,6 @@ export function threadSafeCallback(fn, returnType, argTypes = [], native, option
|
|
|
357
359
|
return cb.pointer;
|
|
358
360
|
},
|
|
359
361
|
});
|
|
362
|
+
Object.defineProperty(wrapper, callbackPointer, { value: cb.pointer });
|
|
360
363
|
return trackCallback(wrapper, fn, "threadSafeCallback");
|
|
361
364
|
}
|
package/lib/core/conversions.js
CHANGED
|
@@ -10,10 +10,24 @@ 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 {
|
|
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";
|
|
14
27
|
|
|
15
28
|
const activeArgumentOwners = argumentOwnerRegistry;
|
|
16
|
-
|
|
29
|
+
// Captured at load so callback dispatch is not affected by later patches.
|
|
30
|
+
const reflectApply = Reflect.apply;
|
|
17
31
|
function retainArgument(owners, value) {
|
|
18
32
|
if (owners !== undefined && value !== null && (typeof value === "object" || typeof value === "function")) owners.push(value);
|
|
19
33
|
}
|
|
@@ -34,7 +48,9 @@ export function argumentsNeedOwners(args) {
|
|
|
34
48
|
// The general fallback receives the hook snapshot taken before any owner probe.
|
|
35
49
|
export function specializeCall(ffiFunc, method, converters, state, invoke, captureHere = true) {
|
|
36
50
|
const [C0, C1, C2, C3, C4, C5] = converters;
|
|
51
|
+
const [N0, N1, N2, N3, N4, N5] = converters.map((convert) => convert.needsOwners ?? needsArgumentOwners);
|
|
37
52
|
const hasAdapters = converters.some((convert) => convert.requiresOwners);
|
|
53
|
+
const sync = method !== "callAsync";
|
|
38
54
|
switch (converters.length) {
|
|
39
55
|
case 0:
|
|
40
56
|
return function () {
|
|
@@ -46,43 +62,42 @@ export function specializeCall(ffiFunc, method, converters, state, invoke, captu
|
|
|
46
62
|
return function (a0) {
|
|
47
63
|
const checked = captureHere ? state.errcheck : null;
|
|
48
64
|
if (checked !== null || arguments.length !== 1) return invoke(arguments, checked);
|
|
49
|
-
if (captureHere && (hasAdapters ||
|
|
65
|
+
if (captureHere && (hasAdapters || N0(a0))) return sync ? callOwned1(ffiFunc, method, C0, a0) : callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
50
66
|
return ffiFunc[method](C0(a0));
|
|
51
67
|
};
|
|
52
68
|
case 2:
|
|
53
69
|
return function (a0, a1) {
|
|
54
70
|
const checked = captureHere ? state.errcheck : null;
|
|
55
71
|
if (checked !== null || arguments.length !== 2) return invoke(arguments, checked);
|
|
56
|
-
if (captureHere && (hasAdapters ||
|
|
72
|
+
if (captureHere && (hasAdapters || N0(a0) || N1(a1))) return sync ? callOwned2(ffiFunc, method, C0, C1, a0, a1) : callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
57
73
|
return ffiFunc[method](C0(a0), C1(a1));
|
|
58
74
|
};
|
|
59
75
|
case 3:
|
|
60
76
|
return function (a0, a1, a2) {
|
|
61
77
|
const checked = captureHere ? state.errcheck : null;
|
|
62
78
|
if (checked !== null || arguments.length !== 3) return invoke(arguments, checked);
|
|
63
|
-
if (captureHere && (hasAdapters ||
|
|
79
|
+
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);
|
|
64
80
|
return ffiFunc[method](C0(a0), C1(a1), C2(a2));
|
|
65
81
|
};
|
|
66
82
|
case 4:
|
|
67
83
|
return function (a0, a1, a2, a3) {
|
|
68
84
|
const checked = captureHere ? state.errcheck : null;
|
|
69
85
|
if (checked !== null || arguments.length !== 4) return invoke(arguments, checked);
|
|
70
|
-
if (captureHere && (hasAdapters ||
|
|
86
|
+
if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
71
87
|
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3));
|
|
72
88
|
};
|
|
73
89
|
case 5:
|
|
74
90
|
return function (a0, a1, a2, a3, a4) {
|
|
75
91
|
const checked = captureHere ? state.errcheck : null;
|
|
76
92
|
if (checked !== null || arguments.length !== 5) return invoke(arguments, checked);
|
|
77
|
-
if (captureHere && (hasAdapters ||
|
|
93
|
+
if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3) || N4(a4))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
78
94
|
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4));
|
|
79
95
|
};
|
|
80
96
|
case 6:
|
|
81
97
|
return function (a0, a1, a2, a3, a4, a5) {
|
|
82
98
|
const checked = captureHere ? state.errcheck : null;
|
|
83
99
|
if (checked !== null || arguments.length !== 6) return invoke(arguments, checked);
|
|
84
|
-
if (captureHere && (hasAdapters ||
|
|
85
|
-
return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
100
|
+
if (captureHere && (hasAdapters || N0(a0) || N1(a1) || N2(a2) || N3(a3) || N4(a4) || N5(a5))) return callWithArgumentOwners(ffiFunc, method, arguments, converters);
|
|
86
101
|
return ffiFunc[method](C0(a0), C1(a1), C2(a2), C3(a3), C4(a4), C5(a5));
|
|
87
102
|
};
|
|
88
103
|
default:
|
|
@@ -93,24 +108,55 @@ export function specializeCall(ffiFunc, method, converters, state, invoke, captu
|
|
|
93
108
|
}
|
|
94
109
|
}
|
|
95
110
|
|
|
111
|
+
// Synchronous owned calls nest strictly: the owners array is a stack entry
|
|
112
|
+
// and the converters run without an intermediate argument array.
|
|
113
|
+
function callOwned1(ffiFunc, method, C0, a0) {
|
|
114
|
+
const owners = [];
|
|
115
|
+
activeOwnerStack.push(owners);
|
|
116
|
+
try {
|
|
117
|
+
return ffiFunc[method](C0(a0, owners));
|
|
118
|
+
} finally {
|
|
119
|
+
activeOwnerStack.pop();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function callOwned2(ffiFunc, method, C0, C1, a0, a1) {
|
|
124
|
+
const owners = [];
|
|
125
|
+
activeOwnerStack.push(owners);
|
|
126
|
+
try {
|
|
127
|
+
return ffiFunc[method](C0(a0, owners), C1(a1, owners));
|
|
128
|
+
} finally {
|
|
129
|
+
activeOwnerStack.pop();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function callOwned3(ffiFunc, method, C0, C1, C2, a0, a1, a2) {
|
|
134
|
+
const owners = [];
|
|
135
|
+
activeOwnerStack.push(owners);
|
|
136
|
+
try {
|
|
137
|
+
return ffiFunc[method](C0(a0, owners), C1(a1, owners), C2(a2, owners));
|
|
138
|
+
} finally {
|
|
139
|
+
activeOwnerStack.pop();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
96
143
|
// The registry is a GC root, including while another converter reenters JS.
|
|
97
144
|
export function callWithArgumentOwners(ffiFunc, method, args, converters, finish, resultHandler, checkedCall) {
|
|
98
145
|
const owners = [];
|
|
99
|
-
|
|
100
|
-
|
|
146
|
+
// Synchronous calls nest strictly, so a stack avoids hashing a fresh array.
|
|
147
|
+
activeOwnerStack.push(owners);
|
|
101
148
|
try {
|
|
102
149
|
const converted = convertArguments(args, converters, owners);
|
|
103
150
|
const result =
|
|
104
151
|
resultHandler === undefined ? ffiFunc[method](...converted) : checkedCall === undefined ? ffiFunc[method === "callAsync" ? "_callAsyncWithErrcheck" : "_callWithErrcheck"](resultHandler, ...converted) : checkedCall(resultHandler, ...converted);
|
|
105
152
|
if (method === "callAsync") {
|
|
106
153
|
const completed = finish === undefined ? result : result.then((value) => finish(value, args));
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return promise;
|
|
154
|
+
activeArgumentOwners.add(owners);
|
|
155
|
+
return completed.finally(() => activeArgumentOwners.delete(owners));
|
|
110
156
|
}
|
|
111
157
|
return finish === undefined ? result : finish(result, args);
|
|
112
158
|
} finally {
|
|
113
|
-
|
|
159
|
+
activeOwnerStack.pop();
|
|
114
160
|
}
|
|
115
161
|
}
|
|
116
162
|
|
|
@@ -181,7 +227,7 @@ const isStructType = (t) => t !== null && (typeof t === "function" || typeof t =
|
|
|
181
227
|
function structArgument(T, index) {
|
|
182
228
|
const instance = typeof T === "function" ? (values) => new T(values) : (structArgumentFactories.get(T) ?? ((values) => T.create(values)));
|
|
183
229
|
const coerce = mirrorsActive ? coerceStructValue : coerceObject;
|
|
184
|
-
|
|
230
|
+
const convert = (a, owners) => {
|
|
185
231
|
a = resolveArgument(a, owners, index);
|
|
186
232
|
retainArgument(owners, a);
|
|
187
233
|
if (Array.isArray(a)) {
|
|
@@ -193,6 +239,10 @@ function structArgument(T, index) {
|
|
|
193
239
|
}
|
|
194
240
|
return coerce(a, owners);
|
|
195
241
|
};
|
|
242
|
+
// A plain object of field values becomes a fresh Buffer passed directly to
|
|
243
|
+
// the call, so nothing else needs to stay reachable.
|
|
244
|
+
convert.needsOwners = (a) => needsArgumentOwners(a) && !(Object.getPrototypeOf(a) === Object.prototype && !("_buffer" in a) && !("_as_parameter_" in a));
|
|
245
|
+
return convert;
|
|
196
246
|
}
|
|
197
247
|
|
|
198
248
|
/**
|
|
@@ -209,13 +259,18 @@ export function coerceValue(a, owners) {
|
|
|
209
259
|
|
|
210
260
|
/**
|
|
211
261
|
* Conversion of an argument beyond `argtypes` (variadic, or without
|
|
212
|
-
* argtypes): a SimpleCData instance
|
|
213
|
-
*
|
|
262
|
+
* argtypes): a numeric SimpleCData instance keeps its type and snapshots its
|
|
263
|
+
* value before the next conversion (`printf("%f", c_double(2.0))`).
|
|
214
264
|
*/
|
|
215
265
|
export function coerceVariadic(a, owners) {
|
|
266
|
+
const info = scalarInstanceInfo(a);
|
|
267
|
+
if (info !== undefined) {
|
|
268
|
+
retainArgument(owners, a);
|
|
269
|
+
return scalarArgumentSnapshot(a, info);
|
|
270
|
+
}
|
|
216
271
|
a = resolveParameter(a, owners);
|
|
217
272
|
retainArgument(owners, a);
|
|
218
|
-
if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return a;
|
|
273
|
+
if (a !== null && typeof a === "object" && a._isSimpleCDataInstance === true) return scalarArgumentSnapshot(a);
|
|
219
274
|
return coerceObject(a, owners);
|
|
220
275
|
}
|
|
221
276
|
|
|
@@ -238,15 +293,16 @@ export function argumentConverters(argTypes, native) {
|
|
|
238
293
|
if (kind === native.CType.STRING || kind === native.CType.WSTRING) return stringArgument(t, kind, index, native);
|
|
239
294
|
if (kind === native.CType.POINTER) return voidPointerArgument(index, native);
|
|
240
295
|
if (typeof t !== "function" || t._isSimpleCData !== true) return coerceObject;
|
|
241
|
-
return scalarArgument(t, index);
|
|
296
|
+
return scalarArgument(t, kind, index);
|
|
242
297
|
};
|
|
243
|
-
|
|
298
|
+
const converters = argTypes.map((t, index) => {
|
|
244
299
|
const base = baseConverter(t, index);
|
|
245
300
|
if (t === null || (typeof t !== "function" && typeof t !== "object")) return base;
|
|
246
301
|
const fromParam = t.from_param;
|
|
247
302
|
if (fromParam === undefined) return base;
|
|
248
303
|
return fromParamArgument(t, base.fromParam ?? base, index, fromParam);
|
|
249
304
|
});
|
|
305
|
+
return converters;
|
|
250
306
|
}
|
|
251
307
|
|
|
252
308
|
function pointerValue(value, native) {
|
|
@@ -308,20 +364,36 @@ function stringArgument(T, kind, index, native) {
|
|
|
308
364
|
return convert;
|
|
309
365
|
}
|
|
310
366
|
|
|
311
|
-
function scalarArgument(T, index) {
|
|
367
|
+
function scalarArgument(T, kind, index) {
|
|
312
368
|
const boolean = T._isBoolean === true;
|
|
313
|
-
|
|
314
|
-
|
|
369
|
+
const stored = (value, info, owners, adapted) => {
|
|
370
|
+
retainArgument(owners, value);
|
|
371
|
+
if (!boolean && info.type !== T && !(value instanceof T) && !(adapted && info.kind === kind)) {
|
|
372
|
+
throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible types, ${info.type.name} instance instead of ${T.name} instance`);
|
|
373
|
+
}
|
|
374
|
+
return scalarArgumentValue(value, info);
|
|
375
|
+
};
|
|
376
|
+
const make = (adapted) => (value, owners) => {
|
|
377
|
+
if (value !== null && (typeof value === "object" || typeof value === "function")) {
|
|
378
|
+
const info = scalarInstanceInfo(value);
|
|
379
|
+
if (info !== undefined) return stored(value, info, owners, adapted);
|
|
380
|
+
value = resolveArgument(value, owners, index);
|
|
381
|
+
}
|
|
315
382
|
if (value === null || typeof value !== "object") return value;
|
|
383
|
+
const info = scalarInstanceInfo(value);
|
|
384
|
+
if (info !== undefined) return stored(value, info, owners, adapted);
|
|
316
385
|
retainArgument(owners, value);
|
|
317
386
|
if (value._isSimpleCDataInstance === true) {
|
|
318
|
-
if (!boolean && !(value instanceof T)) {
|
|
387
|
+
if (!boolean && !(value instanceof T) && !(adapted && scalarArgumentKind(value) === kind)) {
|
|
319
388
|
throw new ArgumentError(`argument ${index + 1}: TypeError: incompatible types, ${value.constructor.name} instance instead of ${T.name} instance`);
|
|
320
389
|
}
|
|
321
|
-
return value
|
|
390
|
+
return scalarArgumentValue(value);
|
|
322
391
|
}
|
|
323
392
|
return objectMemory(value, owners);
|
|
324
393
|
};
|
|
394
|
+
const convert = make(false);
|
|
395
|
+
Object.defineProperty(convert, "fromParam", { value: make(true) });
|
|
396
|
+
return convert;
|
|
325
397
|
}
|
|
326
398
|
|
|
327
399
|
function resolveArgument(value, owners, index) {
|
|
@@ -494,7 +566,7 @@ export function resultConverter(restype) {
|
|
|
494
566
|
return (r) => new restype(copyResultBytes(r));
|
|
495
567
|
}
|
|
496
568
|
if (restype !== null && typeof restype === "object" && restype._isStructType === true) {
|
|
497
|
-
return (r) => restype.toObject(copyResultBytes(r));
|
|
569
|
+
return structResultReaders.get(restype) ?? ((r) => restype.toObject(copyResultBytes(r)));
|
|
498
570
|
}
|
|
499
571
|
return undefined;
|
|
500
572
|
}
|
|
@@ -564,11 +636,23 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
564
636
|
return result !== null && (typeof result === "object" || typeof result === "function") ? coerceValue(result) : result;
|
|
565
637
|
};
|
|
566
638
|
if (!hasScalars && !hasVariants && !hasPointers && !hasStructs) {
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
639
|
+
// The native trampoline passes exactly argTypes.length values with an
|
|
640
|
+
// undefined receiver. Like CPython (tp_call), the handler is invoked
|
|
641
|
+
// directly: own `call`/`apply` properties are not consulted.
|
|
642
|
+
switch (argTypes.length) {
|
|
643
|
+
case 0:
|
|
644
|
+
return () => convertResult(fn());
|
|
645
|
+
case 1:
|
|
646
|
+
return (a0) => convertResult(fn(a0));
|
|
647
|
+
case 2:
|
|
648
|
+
return (a0, a1) => convertResult(fn(a0, a1));
|
|
649
|
+
case 3:
|
|
650
|
+
return (a0, a1, a2) => convertResult(fn(a0, a1, a2));
|
|
651
|
+
default:
|
|
652
|
+
return (...args) => convertResult(reflectApply(fn, undefined, args));
|
|
653
|
+
}
|
|
570
654
|
}
|
|
571
|
-
return
|
|
655
|
+
return (...args) => {
|
|
572
656
|
if (hasScalars) {
|
|
573
657
|
for (let i = 0; i < scalarTypes.length; i++) {
|
|
574
658
|
if (scalarTypes[i] !== null) args[i] = scalarView(scalarTypes[i], args[i]);
|
|
@@ -592,7 +676,7 @@ export function adaptCallbackFunction(fn, argTypes, returnType, native) {
|
|
|
592
676
|
if (structViews[i] !== null) args[i] = structViews[i](args[i]);
|
|
593
677
|
}
|
|
594
678
|
}
|
|
595
|
-
return convertResult(fn
|
|
679
|
+
return convertResult(reflectApply(fn, undefined, args));
|
|
596
680
|
};
|
|
597
681
|
}
|
|
598
682
|
|
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.8.0"
|
|
138
138
|
* ```
|
|
139
139
|
*
|
|
140
140
|
* @category Library Loading
|
package/lib/memory/buffer.js
CHANGED
|
@@ -70,6 +70,30 @@ export function alloc(size) {
|
|
|
70
70
|
return Buffer.alloc(size);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
const kTransientPoolSize = 8192;
|
|
74
|
+
let transientPool = new ArrayBuffer(kTransientPoolSize);
|
|
75
|
+
let transientOffset = 0;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Zero-filled buffer for a value that only lives for one native call. A small
|
|
79
|
+
* Buffer.alloc lives on the V8 heap and must be externalized when native code
|
|
80
|
+
* reads it; slices of an off-heap pool avoid that. Slices are never reused, so
|
|
81
|
+
* a fresh pool is already zeroed.
|
|
82
|
+
*
|
|
83
|
+
* @param {number} size - Size in bytes to allocate
|
|
84
|
+
* @returns {Buffer} Zero-initialized buffer
|
|
85
|
+
*/
|
|
86
|
+
export function allocTransient(size) {
|
|
87
|
+
if (size > kTransientPoolSize >>> 2) return Buffer.alloc(size);
|
|
88
|
+
if (transientOffset + size > kTransientPoolSize) {
|
|
89
|
+
transientPool = new ArrayBuffer(kTransientPoolSize);
|
|
90
|
+
transientOffset = 0;
|
|
91
|
+
}
|
|
92
|
+
const buf = Buffer.from(transientPool, transientOffset, size);
|
|
93
|
+
transientOffset += (size + 7) & ~7;
|
|
94
|
+
return buf;
|
|
95
|
+
}
|
|
96
|
+
|
|
73
97
|
/**
|
|
74
98
|
* Creates a buffer containing a null-terminated C string.
|
|
75
99
|
*
|
|
@@ -2,12 +2,29 @@ import { flush, kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive, refre
|
|
|
2
2
|
import { POINTER_SIZE } from "../../platform/constants.js";
|
|
3
3
|
|
|
4
4
|
const simpleTypes = new WeakSet();
|
|
5
|
+
const scalarInstances = new WeakMap();
|
|
6
|
+
const scalarTypeInfos = new WeakMap();
|
|
7
|
+
const scalarAccessors = [];
|
|
8
|
+
const scalarArgumentKinds = new Set();
|
|
9
|
+
const scalarArgumentTypes = new Map();
|
|
10
|
+
const applyScalarReader = Reflect.apply;
|
|
5
11
|
export const activeArgumentOwners = new Set();
|
|
12
|
+
// GC roots of in-progress synchronous conversions, released in LIFO order.
|
|
13
|
+
export const activeOwnerStack = [];
|
|
6
14
|
export const byrefOwners = new WeakMap();
|
|
7
15
|
export const structArgumentFactories = new WeakMap();
|
|
16
|
+
export const structResultReaders = new WeakMap();
|
|
17
|
+
// Brand of callback wrappers: their constant pointer (the `_as_parameter_`
|
|
18
|
+
// value), read without the generic parameter probes.
|
|
19
|
+
export const callbackPointer = Symbol("callbackPointer");
|
|
8
20
|
|
|
9
21
|
export function resolveParameter(value, owners) {
|
|
10
22
|
if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
|
|
23
|
+
const pointer = value[callbackPointer];
|
|
24
|
+
if (pointer !== undefined) {
|
|
25
|
+
if (owners !== undefined) owners.push(value);
|
|
26
|
+
return pointer;
|
|
27
|
+
}
|
|
11
28
|
if (owners !== undefined) owners.push(value);
|
|
12
29
|
if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
|
|
13
30
|
if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
|
|
@@ -18,11 +35,11 @@ export function resolveParameter(value, owners) {
|
|
|
18
35
|
|
|
19
36
|
// Resolver-only memory operations also retain parents while nested getters can collect.
|
|
20
37
|
const retained = [value];
|
|
21
|
-
|
|
38
|
+
activeOwnerStack.push(retained);
|
|
22
39
|
try {
|
|
23
40
|
return resolveParameter(parameter, retained);
|
|
24
41
|
} finally {
|
|
25
|
-
|
|
42
|
+
activeOwnerStack.pop();
|
|
26
43
|
}
|
|
27
44
|
}
|
|
28
45
|
|
|
@@ -37,6 +54,63 @@ export function sourceBytes(source, offset, size, name) {
|
|
|
37
54
|
|
|
38
55
|
export function registerSimpleType(type) {
|
|
39
56
|
simpleTypes.add(type);
|
|
57
|
+
scalarArgumentKinds.add(type._type);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function scalarTypeInfo(type, swapped = false) {
|
|
61
|
+
let variants = scalarTypeInfos.get(type);
|
|
62
|
+
if (variants === undefined) {
|
|
63
|
+
const kind = type._type;
|
|
64
|
+
variants = [{ type, kind, swapped: false, pointer: type._isPointerValued === true }];
|
|
65
|
+
scalarTypeInfos.set(type, variants);
|
|
66
|
+
}
|
|
67
|
+
const index = swapped ? 1 : 0;
|
|
68
|
+
if (variants[index] === undefined) variants[index] = { ...variants[0], swapped: true };
|
|
69
|
+
return variants[index];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function registerScalarAccessor(accessor) {
|
|
73
|
+
scalarAccessors.push(accessor);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function registerScalarInstance(value, type, swapped = false) {
|
|
77
|
+
scalarInstances.set(value, scalarTypeInfo(type, swapped));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function scalarInstanceInfo(value) {
|
|
81
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) return undefined;
|
|
82
|
+
for (const accessor of scalarAccessors) {
|
|
83
|
+
const info = accessor(value);
|
|
84
|
+
if (info !== undefined) return info;
|
|
85
|
+
}
|
|
86
|
+
return scalarInstances.get(value);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function scalarArgumentKind(value) {
|
|
90
|
+
return scalarInstanceInfo(value)?.kind;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function scalarArgumentValue(value, info = scalarInstanceInfo(value)) {
|
|
94
|
+
if (info === undefined) return value.value;
|
|
95
|
+
const buffer = value._buffer;
|
|
96
|
+
if (mirrorsActive) refresh(buffer);
|
|
97
|
+
const reader = info.swapped ? info.type._readerBE : info.type._reader;
|
|
98
|
+
return applyScalarReader(reader, info.type, [buffer, 0]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function scalarArgumentSnapshot(value, info = scalarInstanceInfo(value)) {
|
|
102
|
+
if (info === undefined || info.pointer || info.kind === 0 || !scalarArgumentKinds.has(info.kind)) return value;
|
|
103
|
+
let constructor = scalarArgumentTypes.get(info.kind);
|
|
104
|
+
if (constructor === undefined) {
|
|
105
|
+
constructor = function ScalarArgument() {};
|
|
106
|
+
Object.defineProperties(constructor, {
|
|
107
|
+
_isSimpleCData: { value: true },
|
|
108
|
+
_type: { value: info.kind },
|
|
109
|
+
});
|
|
110
|
+
scalarArgumentTypes.set(info.kind, constructor);
|
|
111
|
+
}
|
|
112
|
+
// Keep the inferred type, but snapshot the value before the next adapter.
|
|
113
|
+
return { constructor, value: scalarArgumentValue(value, info) };
|
|
40
114
|
}
|
|
41
115
|
|
|
42
116
|
export function isScalarSubclass(type) {
|
|
@@ -49,7 +123,9 @@ export function scalarView(type, buffer, swapped = false) {
|
|
|
49
123
|
const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
|
|
50
124
|
value._buffer = buffer;
|
|
51
125
|
if (base !== undefined) value[kMirrorBase] = base;
|
|
52
|
-
|
|
126
|
+
const useSwapped = !!(swapped && type._readerBE && type._writerBE);
|
|
127
|
+
registerScalarInstance(value, type, useSwapped);
|
|
128
|
+
if (useSwapped) {
|
|
53
129
|
Object.defineProperty(value, "value", {
|
|
54
130
|
get() {
|
|
55
131
|
if (base !== undefined) refresh(buffer);
|
|
@@ -37,7 +37,8 @@ import { bitFieldAccessors } from "./bitfield.js";
|
|
|
37
37
|
import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
|
|
38
38
|
import { buildWrapper } from "./wrap.js";
|
|
39
39
|
import { isMirror, syncDefinition } from "../../memory/mirror.js";
|
|
40
|
-
import {
|
|
40
|
+
import { allocTransient } from "../../memory/buffer.js";
|
|
41
|
+
import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, structResultReaders, writePointerField } from "./common.js";
|
|
41
42
|
|
|
42
43
|
/**
|
|
43
44
|
* Creates a struct type definition with proper alignment and padding.
|
|
@@ -695,11 +696,41 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
|
|
|
695
696
|
|
|
696
697
|
if (fieldDefs.every((field) => !field.isBitField && !field.isNested && !field.isArray && !field.isPointer && !field.type._isPointerValued && !isScalarSubclass(field.type))) {
|
|
697
698
|
const create = structDef.create;
|
|
699
|
+
const set = structDef.set;
|
|
700
|
+
// Only scalar fields: `set` would resolve each name to its precompiled writer.
|
|
701
|
+
const writers = fieldDefs.map((field) => [field.name, fieldWriters[field.name]]);
|
|
702
|
+
const createScalar = (values) => {
|
|
703
|
+
const buf = allocTransient(totalSize);
|
|
704
|
+
for (let i = 0; i < writers.length; i++) {
|
|
705
|
+
const [name, write] = writers[i];
|
|
706
|
+
if (!Object.hasOwn(values, name)) continue;
|
|
707
|
+
const value = values[name];
|
|
708
|
+
if (value !== undefined) write(buf, value);
|
|
709
|
+
}
|
|
710
|
+
return buf;
|
|
711
|
+
};
|
|
712
|
+
const createFast = writers.every(([, write]) => typeof write === "function") ? createScalar : createBuffer;
|
|
698
713
|
structArgumentFactories.set(structDef, (values) => {
|
|
699
714
|
// A later create override must still run, with the definition as receiver.
|
|
700
715
|
const current = structDef.create;
|
|
701
|
-
|
|
716
|
+
if (current !== create) return current.call(structDef, values);
|
|
717
|
+
return structDef.set === set ? createFast(values) : createBuffer(values);
|
|
702
718
|
});
|
|
719
|
+
const toObject = structDef.toObject;
|
|
720
|
+
const readers = fieldDefs.map((field) => [field.name, fieldReaders[field.name]]);
|
|
721
|
+
if (readers.every(([name, read]) => name !== "__proto__" && typeof read === "function")) {
|
|
722
|
+
// Scalar readers return primitives without reentering, so the native
|
|
723
|
+
// result buffer can be read in place; a toObject override gets a copy.
|
|
724
|
+
structResultReaders.set(structDef, (bytes) => {
|
|
725
|
+
if (structDef.toObject !== toObject) return structDef.toObject(Buffer.from(bytes));
|
|
726
|
+
const result = {};
|
|
727
|
+
for (let i = 0; i < readers.length; i++) {
|
|
728
|
+
const [name, read] = readers[i];
|
|
729
|
+
result[name] = read(bytes);
|
|
730
|
+
}
|
|
731
|
+
return result;
|
|
732
|
+
});
|
|
733
|
+
}
|
|
703
734
|
}
|
|
704
735
|
|
|
705
736
|
return syncDefinition(structDef);
|
package/lib/types/SimpleCData.js
CHANGED
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
* ```
|
|
47
47
|
*/
|
|
48
48
|
|
|
49
|
-
import { copyInstance, inDllBuffer, scalarOutparam, scalarView, sourceBytes } from "../structures/helpers/common.js";
|
|
49
|
+
import { copyInstance, inDllBuffer, registerScalarAccessor, scalarOutparam, scalarTypeInfo, scalarView, sourceBytes } from "../structures/helpers/common.js";
|
|
50
50
|
|
|
51
51
|
/**
|
|
52
52
|
* Creates the SimpleCData base class with required dependencies injected.
|
|
@@ -103,12 +103,19 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
|
|
|
103
103
|
* ```
|
|
104
104
|
*/
|
|
105
105
|
class SimpleCData {
|
|
106
|
+
#scalarInfo;
|
|
107
|
+
|
|
108
|
+
static {
|
|
109
|
+
registerScalarAccessor((value) => (#scalarInfo in value ? value.#scalarInfo : undefined));
|
|
110
|
+
}
|
|
111
|
+
|
|
106
112
|
/**
|
|
107
113
|
* @param {number|bigint} [value] - Initial value (default: 0)
|
|
108
114
|
*/
|
|
109
115
|
constructor(value) {
|
|
110
116
|
const Ctor = this.constructor;
|
|
111
117
|
this._buffer = alloc(Ctor._size);
|
|
118
|
+
this.#scalarInfo = scalarTypeInfo(Ctor);
|
|
112
119
|
if (value !== undefined) {
|
|
113
120
|
this.value = value;
|
|
114
121
|
}
|