node-ctypes 2.14.0 → 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.
- package/CHANGELOG.md +27 -1
- 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 +69 -51
- package/lib/core/callback-conversions.js +123 -0
- package/lib/core/callback.js +68 -4
- package/lib/core/conversions.js +74 -412
- package/lib/core/funcptr.js +31 -287
- package/lib/core/invocation.js +170 -0
- package/lib/core/native-aggregate.js +193 -0
- package/lib/core/parameters.js +45 -0
- package/lib/core/paramflags.js +183 -0
- package/lib/core/results.js +86 -0
- package/lib/core/types.js +14 -277
- package/lib/index.js +2 -1
- package/lib/memory/buffer.js +1 -1
- package/lib/memory/mirror.js +2 -2
- package/lib/memory/operations.js +2 -1
- package/lib/memory/ownership.js +218 -0
- package/lib/memory/pointer.js +6 -1
- package/lib/platform/win_types.js +1 -1
- package/lib/structures/Structure.js +50 -37
- package/lib/structures/helpers/array.js +27 -13
- package/lib/structures/helpers/bitfield.js +1 -1
- package/lib/structures/helpers/common.js +3 -368
- package/lib/structures/helpers/fields.js +111 -0
- package/lib/structures/helpers/layout.js +44 -57
- package/lib/structures/helpers/struct.js +19 -108
- package/lib/structures/helpers/union.js +13 -114
- package/lib/structures/helpers/wrap.js +1 -1
- package/lib/structures/protocol.js +8 -0
- package/lib/types/SimpleCData.js +2 -1
- package/lib/types/primitives.js +2 -1
- package/lib/types/scalar-protocol.js +120 -0
- package/package.json +1 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/** Build native by-value ABI descriptors from computed structure and union layouts. */
|
|
2
|
+
import { cacheWeakValue } from "../utils/cache.js";
|
|
3
|
+
|
|
4
|
+
const nativeArrayTypes = new WeakMap();
|
|
5
|
+
const byteArrayTypes = new Map();
|
|
6
|
+
|
|
7
|
+
function byteRun(st, native, offset, length) {
|
|
8
|
+
if (length <= 0) return;
|
|
9
|
+
if (length === 1) {
|
|
10
|
+
st.addField(`__byte@${offset}`, native.CType.UINT8);
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
let arrayType = byteArrayTypes.get(length)?.deref();
|
|
14
|
+
if (arrayType === undefined) {
|
|
15
|
+
arrayType = new native.ArrayType(native.CType.UINT8, length);
|
|
16
|
+
cacheWeakValue(byteArrayTypes, length, arrayType);
|
|
17
|
+
}
|
|
18
|
+
st.addField(`__bytes@${offset}`, arrayType);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const roundUp = (n, a) => Math.ceil(n / a) * a;
|
|
22
|
+
|
|
23
|
+
// Bytes occupied by a bitfield within its storage unit.
|
|
24
|
+
function bitFieldBytes(f) {
|
|
25
|
+
const first = Math.floor(f.bitOffset / 8);
|
|
26
|
+
const last = Math.floor((f.bitOffset + f.bitSize - 1) / 8);
|
|
27
|
+
const bytes = [];
|
|
28
|
+
for (let b = first; b <= last; b++) {
|
|
29
|
+
bytes.push(f.offset + (f.swapped ? f.baseSize - 1 - b : b));
|
|
30
|
+
}
|
|
31
|
+
return bytes;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function aggregateDef(type) {
|
|
35
|
+
if (typeof type === "function") return type._structDef || type._buildStruct?.();
|
|
36
|
+
return type?._isStructType === true ? type : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function arrayLeafDef(array) {
|
|
40
|
+
const element = array.elementType;
|
|
41
|
+
return element?._isArrayType ? arrayLeafDef(element) : aggregateDef(element);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Packed fields inside a nested type can also force memory classification on SysV.
|
|
45
|
+
const unalignedDefs = new WeakMap();
|
|
46
|
+
function hasUnalignedFields(def) {
|
|
47
|
+
let result = unalignedDefs.get(def);
|
|
48
|
+
if (result === undefined) {
|
|
49
|
+
result = def.fields.some((f) => {
|
|
50
|
+
if (f.isBitField || (f.isArray && f.size === 0)) return false;
|
|
51
|
+
if (!def.isUnion && f.offset % (f.naturalAlignment ?? f.alignment) !== 0) return true;
|
|
52
|
+
const nested = f.isArray ? arrayLeafDef(f.type) : f.isNested ? aggregateDef(f.type) : undefined;
|
|
53
|
+
return nested !== undefined && hasUnalignedFields(nested);
|
|
54
|
+
});
|
|
55
|
+
unalignedDefs.set(def, result);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function _buildNativeStructType(def, native) {
|
|
61
|
+
if (def._nativeStructType) return def._nativeStructType;
|
|
62
|
+
if (!Number.isInteger(Math.log2(def.alignment))) {
|
|
63
|
+
throw new TypeError("Native by-value ABI requires power-of-two alignment; use this layout only for memory serialization");
|
|
64
|
+
}
|
|
65
|
+
const st = new native.StructType({
|
|
66
|
+
union: !!def.isUnion,
|
|
67
|
+
alignment: def.alignment,
|
|
68
|
+
memoryClass: hasUnalignedFields(def),
|
|
69
|
+
});
|
|
70
|
+
const fits = (alignment, offset) => alignment <= def.alignment && offset % alignment === 0;
|
|
71
|
+
|
|
72
|
+
// The base layout is the first member; def.fields already includes its fields.
|
|
73
|
+
let fields = def.fields;
|
|
74
|
+
let position = 0;
|
|
75
|
+
if (def.base) {
|
|
76
|
+
if (fits(def.base.alignment, 0)) st.addField("__base__", _buildNativeStructType(def.base, native));
|
|
77
|
+
else byteRun(st, native, 0, def.base.size);
|
|
78
|
+
fields = def.fields.slice(def.base.fields.length);
|
|
79
|
+
position = def.isUnion ? 0 : def.base.size;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (def.isUnion) {
|
|
83
|
+
for (const f of fields) {
|
|
84
|
+
const size = f.isBitField ? f.baseSize : f.size;
|
|
85
|
+
const alignment = f.naturalAlignment ?? f.alignment;
|
|
86
|
+
if (!fits(alignment, 0)) byteRun(st, native, 0, size);
|
|
87
|
+
// A union bitfield occupies its base type at offset zero.
|
|
88
|
+
else if (f.isBitField) st.addField(`__bitfield_${f.name}`, bitFieldBaseType(f));
|
|
89
|
+
else addNativeField(st, f, native);
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
// Capture offsets before resolving types. Field types can run user code.
|
|
93
|
+
const items = [];
|
|
94
|
+
const bitBytes = new Set();
|
|
95
|
+
for (const f of fields) {
|
|
96
|
+
if (f.isBitField) bitFieldBytes(f).forEach((b) => bitBytes.add(b));
|
|
97
|
+
else if (f.size > 0) items.push({ offset: f.offset, size: f.size, field: f });
|
|
98
|
+
}
|
|
99
|
+
for (const b of bitBytes) items.push({ offset: b, size: 1, field: null });
|
|
100
|
+
items.sort((a, b) => a.offset - b.offset);
|
|
101
|
+
|
|
102
|
+
let bytesFrom = -1;
|
|
103
|
+
const flushBytes = () => {
|
|
104
|
+
if (bytesFrom >= 0) byteRun(st, native, bytesFrom, position - bytesFrom);
|
|
105
|
+
bytesFrom = -1;
|
|
106
|
+
};
|
|
107
|
+
const addBytes = (offset, size) => {
|
|
108
|
+
if (bytesFrom < 0) bytesFrom = position;
|
|
109
|
+
position = offset + size;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
for (const { offset, size, field } of items) {
|
|
113
|
+
if (offset < position) continue;
|
|
114
|
+
const alignment = field ? (field.naturalAlignment ?? field.alignment) : 1;
|
|
115
|
+
if (field && fits(alignment, offset)) {
|
|
116
|
+
// Native padding is implicit; larger gaps need explicit bytes.
|
|
117
|
+
if (roundUp(position, alignment) !== offset) addBytes(offset, 0);
|
|
118
|
+
flushBytes();
|
|
119
|
+
addNativeField(st, field, native);
|
|
120
|
+
position = offset + size;
|
|
121
|
+
} else {
|
|
122
|
+
addBytes(offset, size);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
flushBytes();
|
|
126
|
+
// Preserve tail bytes beyond the padding implied by the alignment.
|
|
127
|
+
if (roundUp(position, def.alignment) < def.size) byteRun(st, native, position, def.size - position);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const size = st.getSize();
|
|
131
|
+
if (size !== def.size || st.getAlignment() !== def.alignment) {
|
|
132
|
+
throw new Error(`Native layout of the structure (size ${size}, alignment ${st.getAlignment()}) differs from its definition (size ${def.size}, alignment ${def.alignment})`);
|
|
133
|
+
}
|
|
134
|
+
def._nativeStructType = st;
|
|
135
|
+
return st;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function bitFieldBaseType(f) {
|
|
139
|
+
if (!f.type || typeof f.type._type !== "number") {
|
|
140
|
+
throw new Error(`Bitfield '${f.name}': base type senza _type numerico`);
|
|
141
|
+
}
|
|
142
|
+
return f.type._type;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function inlineArrayType(array, native, fieldName) {
|
|
146
|
+
const own = array._native;
|
|
147
|
+
if (own instanceof native.ArrayType) return own;
|
|
148
|
+
const cached = nativeArrayTypes.get(array);
|
|
149
|
+
if (cached !== undefined) return cached;
|
|
150
|
+
|
|
151
|
+
const element = array.elementType;
|
|
152
|
+
let item;
|
|
153
|
+
if (element?._isArrayType) {
|
|
154
|
+
// Native arrays accept a scalar or struct, not another array. A one-field
|
|
155
|
+
// struct has the row's layout and keeps its ABI types (including floats).
|
|
156
|
+
item = new native.StructType().addField("__row__", inlineArrayType(element, native, fieldName));
|
|
157
|
+
} else {
|
|
158
|
+
const def = aggregateDef(element);
|
|
159
|
+
if (!def) throw new TypeError(`Field '${fieldName}': unsupported inline array element type`);
|
|
160
|
+
item = _buildNativeStructType(def, native);
|
|
161
|
+
}
|
|
162
|
+
const descriptor = new native.ArrayType(item, array.length);
|
|
163
|
+
nativeArrayTypes.set(array, descriptor);
|
|
164
|
+
return descriptor;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function addNativeField(st, f, native) {
|
|
168
|
+
const options = f.isAnonymous ? { anonymous: true } : undefined;
|
|
169
|
+
if (f.isArray) {
|
|
170
|
+
st.addField(f.name, inlineArrayType(f.type, native, f.name), options);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (f.isNested) {
|
|
174
|
+
// A nested member can be a plain definition or a Structure/Union class.
|
|
175
|
+
const nestedDef = aggregateDef(f.type);
|
|
176
|
+
if (!nestedDef || !Array.isArray(nestedDef.fields)) {
|
|
177
|
+
throw new Error(`Field '${f.name}': nested type non riconosciuto`);
|
|
178
|
+
}
|
|
179
|
+
st.addField(f.name, _buildNativeStructType(nestedDef, native), options);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (f.isPointer) {
|
|
183
|
+
st.addField(f.name, native.CType.POINTER);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (f.type && typeof f.type === "function" && f.type._isSimpleCData) {
|
|
187
|
+
st.addField(f.name, f.type._type);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
throw new Error(`Field '${f.name}': tipo non riconosciuto durante _buildNativeStructType`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { _buildNativeStructType as buildNativeAggregate };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Resolve _as_parameter_ while retaining objects across reentrant getters. */
|
|
2
|
+
import { structClass } from "../structures/protocol.js";
|
|
3
|
+
|
|
4
|
+
export const activeArgumentOwners = new Set();
|
|
5
|
+
|
|
6
|
+
// GC roots of in-progress synchronous conversions, released in LIFO order.
|
|
7
|
+
export const activeOwnerStack = [];
|
|
8
|
+
|
|
9
|
+
export const byrefOwners = new WeakMap();
|
|
10
|
+
|
|
11
|
+
// Brand of callback wrappers: their constant pointer (the `_as_parameter_`
|
|
12
|
+
// value), read without the generic parameter probes.
|
|
13
|
+
export const callbackPointer = Symbol("callbackPointer");
|
|
14
|
+
|
|
15
|
+
export function resolveParameter(value, owners, expectedStruct) {
|
|
16
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
|
|
17
|
+
const pointer = value[callbackPointer];
|
|
18
|
+
if (pointer !== undefined) {
|
|
19
|
+
if (owners !== undefined) owners.push(value);
|
|
20
|
+
return pointer;
|
|
21
|
+
}
|
|
22
|
+
if (owners !== undefined) owners.push(value);
|
|
23
|
+
if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
|
|
24
|
+
const actual = expectedStruct === undefined ? undefined : value[structClass];
|
|
25
|
+
if (actual !== undefined) {
|
|
26
|
+
if (actual === expectedStruct || value instanceof expectedStruct) return value;
|
|
27
|
+
// An unrelated aggregate is not interchangeable, but may be an adapter.
|
|
28
|
+
} else if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
|
|
29
|
+
const parameter = value._as_parameter_;
|
|
30
|
+
if (parameter === undefined) {
|
|
31
|
+
if (actual !== undefined) throw new TypeError(`expected ${expectedStruct.name} instance instead of ${actual.name}`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
if (parameter === null || (typeof parameter !== "object" && typeof parameter !== "function")) return parameter;
|
|
35
|
+
if (owners !== undefined) return resolveParameter(parameter, owners, expectedStruct);
|
|
36
|
+
|
|
37
|
+
// Resolver-only memory operations also retain parents while nested getters can collect.
|
|
38
|
+
const retained = [value];
|
|
39
|
+
activeOwnerStack.push(retained);
|
|
40
|
+
try {
|
|
41
|
+
return resolveParameter(parameter, retained, expectedStruct);
|
|
42
|
+
} finally {
|
|
43
|
+
activeOwnerStack.pop();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { isScalarSubclass, scalarOutparam } from "../types/scalar-protocol.js";
|
|
2
|
+
import { callOn } from "./executor.js";
|
|
3
|
+
|
|
4
|
+
function unpackOutput(instance, { dir, simple, outType }) {
|
|
5
|
+
if (dir === "inout") return instance;
|
|
6
|
+
const convert = instance.__ctypes_from_outparam__;
|
|
7
|
+
if (convert === scalarOutparam) return simple ? instance.value : instance;
|
|
8
|
+
if (convert !== undefined) {
|
|
9
|
+
if (typeof convert !== "function") throw new TypeError("__ctypes_from_outparam__ must be callable");
|
|
10
|
+
return convert.call(instance);
|
|
11
|
+
}
|
|
12
|
+
return typeof outType === "function" ? instance : outType.toObject(instance._buffer);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Once the symbol is bound, capture slot metadata. Each call owns its output
|
|
16
|
+
// instances; errcheck may reenter the same wrapper or replace entries in args.
|
|
17
|
+
export function applyParamflags(rawFn, argtypes, paramflags, signature) {
|
|
18
|
+
if (paramflags.length !== argtypes.length) {
|
|
19
|
+
throw new TypeError(`paramflags length (${paramflags.length}) must match argtypes length (${argtypes.length})`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Classify slots and cache pointed-to types for out-params
|
|
23
|
+
const slots = paramflags.map((pf, idx) => {
|
|
24
|
+
if (!["in", "out", "inout"].includes(pf.dir)) throw new TypeError(`paramflags[${idx}] has an invalid direction`);
|
|
25
|
+
const isOut = pf.dir !== "in";
|
|
26
|
+
const argtype = argtypes[idx];
|
|
27
|
+
let outType = null;
|
|
28
|
+
if (isOut) {
|
|
29
|
+
// Expect POINTER(T) argtype; derive base type for read-back
|
|
30
|
+
outType = argtype && argtype._pointerTo ? argtype._pointerTo : null;
|
|
31
|
+
if (!outType) {
|
|
32
|
+
throw new TypeError(`paramflags[${idx}] is "out" but argtype ${idx} is not a POINTER(T)`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { idx, name: pf.name, dir: pf.dir, default: pf.default, outType, simple: outType?._isSimpleCData === true && !isScalarSubclass(outType) };
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const inputs = slots.filter((s) => s.dir !== "out");
|
|
39
|
+
const outputs = slots.filter((s) => s.dir !== "in");
|
|
40
|
+
|
|
41
|
+
let errcheck = null;
|
|
42
|
+
|
|
43
|
+
// `call`: the callOn target when `method` is "callOn".
|
|
44
|
+
const invokeWithFlags = (method, callArgs, call) => {
|
|
45
|
+
const checked = errcheck;
|
|
46
|
+
const namedForm =
|
|
47
|
+
callArgs.length === 1 &&
|
|
48
|
+
callArgs[0] !== null &&
|
|
49
|
+
typeof callArgs[0] === "object" &&
|
|
50
|
+
!Buffer.isBuffer(callArgs[0]) &&
|
|
51
|
+
!ArrayBuffer.isView(callArgs[0]) &&
|
|
52
|
+
!(callArgs[0] instanceof ArrayBuffer) &&
|
|
53
|
+
!Array.isArray(callArgs[0]) &&
|
|
54
|
+
// Exclude struct/union proxies (they have _buffer)
|
|
55
|
+
callArgs[0]._buffer === undefined;
|
|
56
|
+
|
|
57
|
+
const rawArgs = new Array(slots.length);
|
|
58
|
+
|
|
59
|
+
// Populate in-slots
|
|
60
|
+
let posIdx = 0;
|
|
61
|
+
for (const input of inputs) {
|
|
62
|
+
let value;
|
|
63
|
+
if (namedForm) {
|
|
64
|
+
value = callArgs[0][input.name];
|
|
65
|
+
if (value === undefined) value = input.default;
|
|
66
|
+
} else {
|
|
67
|
+
value = posIdx < callArgs.length ? callArgs[posIdx++] : input.default;
|
|
68
|
+
}
|
|
69
|
+
if (value === undefined) {
|
|
70
|
+
throw new TypeError(`paramflags: missing required arg "${input.name}"`);
|
|
71
|
+
}
|
|
72
|
+
rawArgs[input.idx] = value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Keep the original instances: errcheck can replace entries in rawArgs.
|
|
76
|
+
const instances =
|
|
77
|
+
outputs.length === 0
|
|
78
|
+
? null
|
|
79
|
+
: outputs.map(({ idx, dir, outType, name }) => {
|
|
80
|
+
const instance = dir === "inout" ? rawArgs[idx] : newOutInstance(outType, name);
|
|
81
|
+
rawArgs[idx] = instance;
|
|
82
|
+
return instance;
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const finish = (result) => {
|
|
86
|
+
// Returning the original args continues normal output unpacking.
|
|
87
|
+
if (checked !== null) {
|
|
88
|
+
const value = checked(result, paramflagsWrapper, rawArgs);
|
|
89
|
+
if (value !== rawArgs) return value;
|
|
90
|
+
}
|
|
91
|
+
if (instances === null) return result;
|
|
92
|
+
if (instances.length === 1) return unpackOutput(instances[0], outputs[0]);
|
|
93
|
+
return instances.map((instance, i) => unpackOutput(instance, outputs[i]));
|
|
94
|
+
};
|
|
95
|
+
// The private binding snapshots this handler and keeps adapter temporaries
|
|
96
|
+
// alive until output processing finishes, including on an async rejection.
|
|
97
|
+
const previous = rawFn.errcheck;
|
|
98
|
+
rawFn.errcheck = finish;
|
|
99
|
+
try {
|
|
100
|
+
if (method === "callOn") return rawFn._callOn(call, rawArgs);
|
|
101
|
+
return method === "callAsync" ? rawFn.callAsync(...rawArgs) : rawFn(...rawArgs);
|
|
102
|
+
} finally {
|
|
103
|
+
rawFn.errcheck = previous;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
let paramflagsWrapper;
|
|
108
|
+
if (inputs.length > 0 && outputs.length === 0 && signature.represent === undefined && signature.check === undefined && signature.converters.every((convert) => convert.passesPrimitives === true)) {
|
|
109
|
+
paramflagsWrapper = (...args) => {
|
|
110
|
+
// Exact positional numbers need no defaults, owners or output conversion.
|
|
111
|
+
// A reentrant call can still have an outer handler on the private binding.
|
|
112
|
+
if (errcheck === null && args.length === inputs.length && args.every(Number.isFinite) && rawFn.errcheck === null) return rawFn(...args);
|
|
113
|
+
return invokeWithFlags("call", args);
|
|
114
|
+
};
|
|
115
|
+
} else {
|
|
116
|
+
paramflagsWrapper = (...args) => invokeWithFlags("call", args);
|
|
117
|
+
}
|
|
118
|
+
Object.defineProperties(paramflagsWrapper, {
|
|
119
|
+
funcName: { value: rawFn.funcName },
|
|
120
|
+
address: { value: rawFn.address },
|
|
121
|
+
_as_parameter_: { value: rawFn.address },
|
|
122
|
+
_ffi: { value: rawFn._ffi },
|
|
123
|
+
callAsync: { value: (...args) => invokeWithFlags("callAsync", args) },
|
|
124
|
+
callOn: { value: (target, ...args) => callOn(paramflagsWrapper, target, args) },
|
|
125
|
+
_callOn: { value: (call, args) => invokeWithFlags("callOn", args, call) },
|
|
126
|
+
errcheck: {
|
|
127
|
+
get: () => errcheck,
|
|
128
|
+
set: (callback) => {
|
|
129
|
+
if (callback !== null && callback !== undefined && typeof callback !== "function") {
|
|
130
|
+
throw new TypeError("errcheck must be a function or null");
|
|
131
|
+
}
|
|
132
|
+
errcheck = callback ?? null;
|
|
133
|
+
},
|
|
134
|
+
enumerable: false,
|
|
135
|
+
configurable: true,
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
return paramflagsWrapper;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function newOutInstance(type, name) {
|
|
142
|
+
if (typeof type === "function" && (type._isSimpleCData || type._isArrayType || typeof type._buildStruct === "function")) {
|
|
143
|
+
return new type();
|
|
144
|
+
}
|
|
145
|
+
if (type && typeof type === "object" && typeof type.create === "function") {
|
|
146
|
+
return type.create();
|
|
147
|
+
}
|
|
148
|
+
throw new TypeError(`paramflags "out" param "${name}": cannot determine the target type`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Normalize a paramflags entry: Python tuple `[flag, name, default]`
|
|
153
|
+
* (flag 1 = in, 2 = out, 3 = inout, 4 = in defaulting to 0) or `{ dir, name, default }`.
|
|
154
|
+
* @private
|
|
155
|
+
*/
|
|
156
|
+
function toParamFlag(pf) {
|
|
157
|
+
if (!Array.isArray(pf)) return pf;
|
|
158
|
+
const [flag = 1, name, ...rest] = pf;
|
|
159
|
+
const dir = (flag & 3) === 3 ? "inout" : flag & 2 ? "out" : "in";
|
|
160
|
+
const result = { dir, name };
|
|
161
|
+
if (rest.length > 0) result.default = rest[0];
|
|
162
|
+
else if (flag & 4) result.default = 0;
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function normalizeParamflags(paramflags, argtypes) {
|
|
167
|
+
// Only shape and pointer requirements precede lookup. Names, defaults and
|
|
168
|
+
// full direction validation belong to the successfully bound wrapper.
|
|
169
|
+
if (!Array.isArray(paramflags)) {
|
|
170
|
+
throw new TypeError("paramflags must be an array");
|
|
171
|
+
}
|
|
172
|
+
paramflags = paramflags.map(toParamFlag);
|
|
173
|
+
if (paramflags.length !== argtypes.length) {
|
|
174
|
+
throw new TypeError(`paramflags length (${paramflags.length}) must match argtypes length (${argtypes.length})`);
|
|
175
|
+
}
|
|
176
|
+
for (let i = 0; i < paramflags.length; i++) {
|
|
177
|
+
const pf = paramflags[i];
|
|
178
|
+
if (pf.dir !== "in" && !(argtypes[i] && argtypes[i]._pointerTo)) {
|
|
179
|
+
throw new TypeError(`paramflags[${i}] is "out" but argtype ${i} is not a POINTER(T)`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return paramflags;
|
|
183
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** Result representation and checks captured from a declared restype. */
|
|
2
|
+
import { kFromBytes } from "../structures/Structure.js";
|
|
3
|
+
import { structResultReaders } from "../structures/protocol.js";
|
|
4
|
+
import { isScalarSubclass, scalarView } from "../types/scalar-protocol.js";
|
|
5
|
+
import { requireDescriptor } from "./types.js";
|
|
6
|
+
|
|
7
|
+
const reflectApply = Reflect.apply;
|
|
8
|
+
|
|
9
|
+
function copyResultBytes(result) {
|
|
10
|
+
const bytes = Buffer.alloc(result.length);
|
|
11
|
+
bytes.set(result);
|
|
12
|
+
return bytes;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Python restype conversion done in JS: `POINTER(T)` returns a pointer object
|
|
17
|
+
* (`null` for NULL), a CFUNCTYPE type returns a callable. Undefined when the
|
|
18
|
+
* native result is already final.
|
|
19
|
+
*
|
|
20
|
+
* @param {*} restype - Declared return type
|
|
21
|
+
* @param {Object} native - Native descriptor classes
|
|
22
|
+
* @returns {Function|undefined} Converter `(result, owned = false)`; async
|
|
23
|
+
* completion owns its struct buffer, while a sync call may reuse it.
|
|
24
|
+
*/
|
|
25
|
+
export function resultConverter(restype, native) {
|
|
26
|
+
if (isScalarSubclass(restype)) return (bytes) => scalarView(restype, bytes);
|
|
27
|
+
if (restype?._isVariantBool === true) return (result) => result !== 0;
|
|
28
|
+
if (restype !== null && typeof restype === "object" && restype._pointerTo !== undefined) {
|
|
29
|
+
return (r) => (r === null || r === 0n ? null : restype.fromAddress(r));
|
|
30
|
+
}
|
|
31
|
+
if (typeof restype === "function" && restype._isFuncPtr === true) {
|
|
32
|
+
return (r) => (r === null || r === 0n ? null : restype(r));
|
|
33
|
+
}
|
|
34
|
+
if (typeof restype === "function" && typeof restype._buildStruct === "function") {
|
|
35
|
+
// Materialize the C value without running subclass initializers.
|
|
36
|
+
const materialize = restype[kFromBytes].bind(restype);
|
|
37
|
+
return (bytes, owned = false) => materialize(owned ? bytes : copyResultBytes(bytes));
|
|
38
|
+
}
|
|
39
|
+
if (restype !== null && typeof restype === "object" && restype._isStructType === true) {
|
|
40
|
+
// toObject may retain array views or union getters over its input.
|
|
41
|
+
return structResultReaders.get(restype) ?? ((r) => restype.toObject(copyResultBytes(r)));
|
|
42
|
+
}
|
|
43
|
+
if (restype !== null && typeof restype === "object" && restype._isArrayType !== true) requireDescriptor(restype, native);
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function scalarResult(restype) {
|
|
48
|
+
return isScalarSubclass(restype);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function resultCheck(restype, name, loader = "FFI") {
|
|
52
|
+
const check = restype?._check_retval_;
|
|
53
|
+
const hresult = restype?._isHResult === true;
|
|
54
|
+
if (!hresult && check === undefined) return undefined;
|
|
55
|
+
return (result) => {
|
|
56
|
+
if (check !== undefined && typeof check !== "function") throw new TypeError("_check_retval_ must be callable");
|
|
57
|
+
if (hresult) {
|
|
58
|
+
const value = result?._isSimpleCDataInstance === true ? result.value : result;
|
|
59
|
+
const number = typeof value === "bigint" ? Number(value) : value;
|
|
60
|
+
if (typeof number === "number" && number < 0) {
|
|
61
|
+
const hex = (number >>> 0).toString(16).padStart(8, "0").toUpperCase();
|
|
62
|
+
const error = new Error(`${loader} '${name}' failed with HRESULT 0x${hex}`);
|
|
63
|
+
error.hresult = number;
|
|
64
|
+
error.winerror = number >>> 0;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return check === undefined ? result : reflectApply(check, restype, [result]);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* True when `restype` is a struct or union returned by value: the native
|
|
74
|
+
* function must then return its bytes (FFIFunction option `struct_buffer`),
|
|
75
|
+
* which {@link resultConverter} turns into the result.
|
|
76
|
+
*
|
|
77
|
+
* @param {*} restype - Declared return type
|
|
78
|
+
* @returns {boolean}
|
|
79
|
+
*/
|
|
80
|
+
export function structResult(restype) {
|
|
81
|
+
return (typeof restype === "function" && typeof restype._buildStruct === "function") || (restype !== null && typeof restype === "object" && restype._isStructType === true);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function composeResult(represent, check) {
|
|
85
|
+
return check === undefined ? represent : (value, owned) => check(represent === undefined ? value : represent(value, owned));
|
|
86
|
+
}
|