node-ctypes 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -13
- package/build/Release/ctypes-darwin-arm64.node +0 -0
- package/build/Release/ctypes-darwin-x64.node +0 -0
- package/build/Release/ctypes-linux-arm64-musl.node +0 -0
- package/build/Release/ctypes-linux-arm64.node +0 -0
- package/build/Release/ctypes-linux-x64-musl.node +0 -0
- package/build/Release/ctypes-linux-x64.node +0 -0
- package/build/Release/ctypes-win32-arm64.node +0 -0
- package/build/Release/ctypes-win32-x64.node +0 -0
- package/lib/core/Library.js +86 -76
- package/lib/core/callback.js +10 -17
- package/lib/core/conversions.js +172 -4
- package/lib/core/funcptr.js +63 -46
- package/lib/core/lazy-loader.js +10 -4
- package/lib/core/types.js +196 -98
- package/lib/index.d.ts +163 -35
- package/lib/index.js +36 -26
- package/lib/memory/buffer.js +45 -16
- package/lib/memory/operations.js +55 -43
- package/lib/memory/pointer.js +135 -26
- package/lib/platform/constants.js +0 -1
- package/lib/platform/errors.js +48 -4
- package/lib/platform/find_library.js +78 -19
- package/lib/structures/Structure.js +258 -178
- package/lib/structures/Union.js +10 -21
- package/lib/structures/helpers/array.js +71 -4
- package/lib/structures/helpers/bitfield.js +66 -150
- package/lib/structures/helpers/common.js +115 -15
- package/lib/structures/helpers/layout.js +131 -0
- package/lib/structures/helpers/struct.js +142 -400
- package/lib/structures/helpers/union.js +130 -141
- package/lib/structures/helpers/wrap.js +3 -15
- package/lib/types/primitives.js +130 -101
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -115,9 +115,24 @@ const name = array(c_char, 16)();
|
|
|
115
115
|
name.value = "node"; // .value / .raw as in Python
|
|
116
116
|
```
|
|
117
117
|
|
|
118
|
+
An array type in `argtypes` is passed by address, as in C and Python
|
|
119
|
+
(`fill.argtypes = [c_int32 * 4]`). As in Python, the argument must be an
|
|
120
|
+
instance of an array with the same element type and length; a Buffer or a
|
|
121
|
+
typed array is also accepted as its memory. Other values raise
|
|
122
|
+
`ArgumentError`.
|
|
123
|
+
|
|
118
124
|
Nested structs, anonymous fields (`static _anonymous_ = ["data"]`),
|
|
119
|
-
explicit packing (`static _pack_ = 1`),
|
|
120
|
-
(`POINTER(() => Node)`)
|
|
125
|
+
explicit packing (`static _pack_ = 1`), minimum alignment
|
|
126
|
+
(`static _align_ = 16`), self-referential pointers (`POINTER(() => Node)`)
|
|
127
|
+
and subclasses that add fields to their base class all work identically to
|
|
128
|
+
Python. The layout of bit fields follows Python's `_layout_`: `"gcc-sysv"`
|
|
129
|
+
by default, `"ms"` on Windows or with `_pack_`. Bit fields wider than 53
|
|
130
|
+
bits read as BigInt.
|
|
131
|
+
|
|
132
|
+
Structures and unions passed or returned by value keep this layout, also
|
|
133
|
+
with `_pack_`: as with GCC and clang, a structure with misaligned fields is
|
|
134
|
+
passed in memory on x86-64 System V (Linux, macOS Intel), where Python
|
|
135
|
+
ctypes passes it in registers and the called function reads wrong values.
|
|
121
136
|
|
|
122
137
|
### Pointers, buffers, and cast
|
|
123
138
|
|
|
@@ -189,12 +204,19 @@ with the `using` declaration for scope-bound cleanup (also on `throw`):
|
|
|
189
204
|
} // close() + release() run automatically
|
|
190
205
|
```
|
|
191
206
|
|
|
207
|
+
A function keeps its library loaded as long as it is referenced, also when
|
|
208
|
+
the `CDLL` object itself is no longer used. After `close()`, its functions
|
|
209
|
+
throw instead of calling unloaded code; `close()` itself throws while a call
|
|
210
|
+
to one of them is in progress (from a callback, or a pending `callAsync()`).
|
|
211
|
+
|
|
192
212
|
Set `NODE_CTYPES_DEBUG_CALLBACKS=1` to log a stack trace for every
|
|
193
213
|
callback garbage-collected without `.release()`.
|
|
194
214
|
|
|
195
215
|
Callbacks invoked by native threads need `threadSafeCallback()`: the
|
|
196
216
|
JavaScript function runs on the main thread, and the calling thread waits
|
|
197
|
-
for its result
|
|
217
|
+
for its result (several threads can call it at the same time; each gets the
|
|
218
|
+
result of its own call, `0` if the function throws). Like a timer, a
|
|
219
|
+
thread-safe callback keeps the event loop
|
|
198
220
|
alive until released; `.unref()` lets the process exit when nothing else
|
|
199
221
|
is pending (calls are still delivered while it runs), `.ref()` restores it:
|
|
200
222
|
|
|
@@ -207,8 +229,11 @@ startWorker(onEvent); // a native library calling onEvent from its own thread
|
|
|
207
229
|
|
|
208
230
|
`GetLastError()` / `get_errno()` read a **private thread-local slot** —
|
|
209
231
|
exactly like Python's `ctypes.get_last_error()` / `ctypes.get_errno()`.
|
|
210
|
-
The slot is
|
|
211
|
-
`use_last_error` or `use_errno`; otherwise it stays at 0.
|
|
232
|
+
The slot is used **only** by FFI calls through libraries opened with
|
|
233
|
+
`use_last_error` or `use_errno`; otherwise it stays at 0. As in Python
|
|
234
|
+
those calls swap it with the system value: the function sees the value set
|
|
235
|
+
with `set_errno()` / `set_last_error()`, the value it leaves becomes the
|
|
236
|
+
private one, and the system value is restored after the call.
|
|
212
237
|
|
|
213
238
|
```javascript
|
|
214
239
|
const user32 = new WinDLL("user32.dll", { use_last_error: true });
|
|
@@ -277,10 +302,13 @@ const [p2, t2] = fn({ hWnd }); // or named-args
|
|
|
277
302
|
|
|
278
303
|
fn.errcheck = (result, func, args) => {
|
|
279
304
|
if (!result) throw new Error("call failed");
|
|
280
|
-
return
|
|
305
|
+
return args; // args: the arguments, out params as instances (args[1].value)
|
|
281
306
|
};
|
|
282
307
|
```
|
|
283
308
|
|
|
309
|
+
As in Python, the value returned by `errcheck` is the result of the call,
|
|
310
|
+
unless it is `args` itself: then the out-params are returned.
|
|
311
|
+
|
|
284
312
|
### Sharing memory with existing buffers
|
|
285
313
|
|
|
286
314
|
```javascript
|
|
@@ -337,6 +365,10 @@ const abs = libc.func("abs", c_int32, [StrLen]);
|
|
|
337
365
|
abs("hello"); // 5
|
|
338
366
|
```
|
|
339
367
|
|
|
368
|
+
As in Python, `from_param` receives the argument as passed (also with
|
|
369
|
+
`CFUNCTYPE` prototypes), its result is converted as the declared type, and
|
|
370
|
+
an error it throws becomes `ArgumentError` (`"argument 1: RangeError: ..."`).
|
|
371
|
+
|
|
340
372
|
### Big-endian structures
|
|
341
373
|
|
|
342
374
|
```javascript
|
|
@@ -471,7 +503,9 @@ Plus the Win32 types, structures and pointer types of `ctypes.wintypes` under `w
|
|
|
471
503
|
|
|
472
504
|
### What works identically
|
|
473
505
|
|
|
474
|
-
Structs, unions, bit fields
|
|
506
|
+
Structs, unions, bit fields (`_layout_` `"gcc-sysv"` / `"ms"`), anonymous
|
|
507
|
+
fields, `_pack_`, `_align_`, subclasses of structures and unions, nested layouts,
|
|
508
|
+
structures and unions by value (a struct `restype` returns an instance),
|
|
475
509
|
arrays (also of arrays, pointers and function pointers), pointers and
|
|
476
510
|
pointer arithmetic (also `POINTER(POINTER(T))`), callbacks (`CFUNCTYPE` /
|
|
477
511
|
`WINFUNCTYPE`, also as struct fields), `prototype((name, dll), paramflags)`,
|
|
@@ -501,13 +535,32 @@ pointer arithmetic (also `POINTER(POINTER(T))`), callbacks (`CFUNCTYPE` /
|
|
|
501
535
|
(Python: Windows only), so the same code runs everywhere.
|
|
502
536
|
- **64-bit and pointer-sized integers** (`c_int64`, `c_uint64`,
|
|
503
537
|
`c_size_t`, `c_ssize_t`) also accept `null` (as 0) and a `Buffer`
|
|
504
|
-
(as its address).
|
|
538
|
+
(as its address) as arguments.
|
|
539
|
+
- **Variadic arguments follow the C promotions**: a `c_float`, `c_int8`,
|
|
540
|
+
`c_char`, … instance passed beyond `argtypes` is passed as `double` /
|
|
541
|
+
`int`, where Python fails (`ffi_prep_cif_var failed`).
|
|
542
|
+
- **A plain object is accepted for a structure argument** passed by value
|
|
543
|
+
(fields by name).
|
|
544
|
+
- **`c_wchar` also accepts a code point** (`new c_wchar(0x4E2D)`), where
|
|
545
|
+
Python requires a 1-character string.
|
|
546
|
+
- **`memmove()` / `memset()` stop at the end of JS memory** (Buffer, typed
|
|
547
|
+
array, `ArrayBuffer`) instead of writing past it.
|
|
548
|
+
- **Integer types reject non-integral numbers** (`3.7`, `NaN`) as Python
|
|
549
|
+
rejects floats; JS has no int/float distinction, so `3.0` is accepted.
|
|
550
|
+
- **Array instances are Buffers whose Array methods work on the elements**
|
|
551
|
+
(`slice`, `map`, `includes`, …, as Python sequences); the Buffer methods
|
|
552
|
+
(`readInt32LE`, `subarray`, …) work on the bytes.
|
|
553
|
+
- **Unions by value on x86-64 System V** are passed with the ABI rules;
|
|
554
|
+
Python passes them in the wrong registers (libffi#33).
|
|
555
|
+
- **Structure/Union fields are accessors of the class**, as Python fields
|
|
556
|
+
are descriptors (`vars(s)` is empty): `Object.keys(s)` and `{ ...s }` do
|
|
557
|
+
not list them; use `s.toObject()`. `JSON.stringify(s)` and
|
|
558
|
+
`console.log(s)` show the fields.
|
|
505
559
|
|
|
506
560
|
### Not supported
|
|
507
561
|
|
|
508
|
-
- **`ctypes.resize(instance, size)`** —
|
|
509
|
-
|
|
510
|
-
place, and re-pointing the Proxy target would break identity.
|
|
562
|
+
- **`ctypes.resize(instance, size)`** — Structure/Union instances use a
|
|
563
|
+
Node `Buffer`, and Buffers aren't resizable in place.
|
|
511
564
|
Work-around: `new MyStruct(myBuffer)` with a pre-sized buffer.
|
|
512
565
|
- **`c_longdouble`** (80/128-bit float, `ffi_type_longdouble`) — rarely
|
|
513
566
|
used; fall back to `c_double` or raw bytes.
|
|
@@ -523,9 +576,9 @@ needs these changes:
|
|
|
523
576
|
| `POINTER(T)` restype returned a `bigint` address | returns a pointer object (`null` for NULL); use `.address` for the number |
|
|
524
577
|
| NULL `POINTER` struct fields were pointer objects | they are `null` |
|
|
525
578
|
| `c_char` values were numbers | 1-character strings; `c_char * n` fields read/write as strings |
|
|
526
|
-
| invalid `c_char` values were truncated | `TypeError` (`"one character bytes, bytearray or integer expected"`) |
|
|
579
|
+
| invalid `c_char` values were truncated | `TypeError` (`"one character bytes, bytearray, or an integer in range(256) expected, not ..."`) |
|
|
527
580
|
| wrong argument types raised `TypeError` | raise `ArgumentError` (a `TypeError` subclass), message `"argument N: TypeError: ..."` |
|
|
528
|
-
| unsupported pointer arguments (functions, plain objects) passed NULL | raise `ArgumentError` (`"
|
|
581
|
+
| unsupported pointer arguments (functions, plain objects) passed NULL | raise `ArgumentError` (`"'function' object cannot be interpreted as ctypes.c_void_p"`) |
|
|
529
582
|
| functions without `restype` / `argtypes` | default `restype` is `c_int`; without `argtypes` the call uses the fixed-argument ABI |
|
|
530
583
|
| `create_string_buffer(init)` | also takes `size` and returns a Buffer with `.value` / `.raw` |
|
|
531
584
|
| `c_long` / `c_ulong` (and `BOOL`, `LONG`, `DWORD`, `ULONG`) fields and `.value` were numbers on Windows | `BigInt` on every platform, like function results; writes accept numbers and BigInt |
|
|
@@ -551,6 +604,11 @@ Each example in `examples/` has its own README; see the [index](examples/README.
|
|
|
551
604
|
|
|
552
605
|
## Tests & docs
|
|
553
606
|
|
|
607
|
+
`npm test` first builds a small C library (`tests/fixtures/`, into
|
|
608
|
+
`build/fixture/`) used by the tests of structures by value, array parameters
|
|
609
|
+
and reentrant calls; `npm run build:test-fixture` builds it alone. Python
|
|
610
|
+
twins of the tests (`tests/common/*.py`) load the same library.
|
|
611
|
+
|
|
554
612
|
```bash
|
|
555
613
|
cd tests && npm install && npm run test # unit tests (JS + Python parity)
|
|
556
614
|
NODE_CTYPES_NO_EXTERNAL_BUFFERS=1 npm test # again as in Electron (from tests/)
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/lib/core/Library.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
*/
|
|
41
41
|
|
|
42
42
|
import { _toNativeReturnType } from "./types.js";
|
|
43
|
-
import { adaptCallbackFunction, argumentConverters, convertArguments,
|
|
43
|
+
import { adaptCallbackFunction, argumentConverters, convertArguments, resultConverter, structResult } from "./conversions.js";
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
46
|
* Creates the Library-related classes with required dependencies injected.
|
|
@@ -57,6 +57,10 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
57
57
|
// Chiave di cache di un tipo: i tipi oggetto/classe (POINTER, struct, ...) hanno
|
|
58
58
|
// un id stabile; `${tipo}` darebbe "[object Object]" per tutti i POINTER.
|
|
59
59
|
const typeIds = new WeakMap();
|
|
60
|
+
// Funzione passata a errcheck quando la chiamata passa da un attributo
|
|
61
|
+
// della libreria (FunctionWrapper).
|
|
62
|
+
const kErrcheckFunc = Symbol("errcheckFunc");
|
|
63
|
+
|
|
60
64
|
let nextTypeId = 0;
|
|
61
65
|
const typeKey = (t) => {
|
|
62
66
|
if (t === null || (typeof t !== "object" && typeof t !== "function")) return String(t);
|
|
@@ -68,16 +72,33 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
68
72
|
return id;
|
|
69
73
|
};
|
|
70
74
|
|
|
75
|
+
// Chiave di cache delle opzioni di func() (abi, ...), indipendente dall'ordine.
|
|
76
|
+
const optionsKey = (options) => {
|
|
77
|
+
let key = "";
|
|
78
|
+
for (const name of Object.keys(options).sort()) {
|
|
79
|
+
key += `;${name}=${typeKey(options[name])}`;
|
|
80
|
+
}
|
|
81
|
+
return key;
|
|
82
|
+
};
|
|
83
|
+
|
|
71
84
|
class FunctionWrapper {
|
|
72
85
|
constructor(cdll, name) {
|
|
73
86
|
const argtypes = [];
|
|
74
87
|
let restype = undefined;
|
|
88
|
+
let errcheck = null;
|
|
75
89
|
let cachedFunc = null;
|
|
76
90
|
|
|
77
|
-
// Python ctypes: restype predefinito c_int.
|
|
91
|
+
// Python ctypes: restype predefinito c_int. Ogni attributo (libc.abs) ha
|
|
92
|
+
// la sua funzione, non quella condivisa dalla cache di func(): errcheck
|
|
93
|
+
// non tocca altri utenti della stessa firma e resta dopo un cambio di
|
|
94
|
+
// argtypes / restype, come in Python.
|
|
78
95
|
const resolve = () => {
|
|
79
96
|
if (!cachedFunc) {
|
|
80
|
-
cachedFunc = cdll.
|
|
97
|
+
cachedFunc = cdll._createFunction(name, restype === undefined ? FunctionWrapper.defaultRestype : restype, argtypes);
|
|
98
|
+
Object.defineProperty(cachedFunc, kErrcheckFunc, { value: func });
|
|
99
|
+
if (errcheck !== null) {
|
|
100
|
+
cachedFunc.errcheck = errcheck;
|
|
101
|
+
}
|
|
81
102
|
}
|
|
82
103
|
return cachedFunc;
|
|
83
104
|
};
|
|
@@ -90,7 +111,8 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
90
111
|
argtypes: {
|
|
91
112
|
get: () => argtypes,
|
|
92
113
|
set: (value) => {
|
|
93
|
-
argtypes
|
|
114
|
+
// Python: argtypes = None toglie i tipi degli argomenti.
|
|
115
|
+
argtypes.splice(0, argtypes.length, ...(value ?? []));
|
|
94
116
|
cachedFunc = null; // Invalidate cache
|
|
95
117
|
},
|
|
96
118
|
configurable: true,
|
|
@@ -104,9 +126,12 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
104
126
|
configurable: true,
|
|
105
127
|
},
|
|
106
128
|
errcheck: {
|
|
107
|
-
get: () =>
|
|
129
|
+
get: () => errcheck,
|
|
108
130
|
set: (value) => {
|
|
109
|
-
|
|
131
|
+
errcheck = value ?? null;
|
|
132
|
+
if (cachedFunc) {
|
|
133
|
+
cachedFunc.errcheck = errcheck;
|
|
134
|
+
}
|
|
110
135
|
},
|
|
111
136
|
configurable: true,
|
|
112
137
|
},
|
|
@@ -131,7 +156,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
131
156
|
if (typeof options === "number") {
|
|
132
157
|
options = { mode: options };
|
|
133
158
|
}
|
|
134
|
-
this._lib =
|
|
159
|
+
this._lib = new Library(libPath, options.mode, options.winmode);
|
|
135
160
|
// Use LRU cache to prevent unbounded memory growth
|
|
136
161
|
const cacheSize = options.cacheSize ?? 1000;
|
|
137
162
|
this._cache = new LRUCache(cacheSize);
|
|
@@ -172,17 +197,35 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
172
197
|
* @returns {Function} Funzione callable
|
|
173
198
|
*/
|
|
174
199
|
func(name, returnType, argTypes = [], options = {}) {
|
|
175
|
-
const cacheKey = `${name}:${typeKey(returnType)}:${argTypes.map(typeKey).join(",")}`;
|
|
176
|
-
|
|
177
|
-
if (
|
|
178
|
-
|
|
200
|
+
const cacheKey = `${name}:${typeKey(returnType)}:${argTypes.map(typeKey).join(",")}${optionsKey(options)}`;
|
|
201
|
+
let fn = this._cache.get(cacheKey);
|
|
202
|
+
if (fn === undefined) {
|
|
203
|
+
fn = this._createFunction(name, returnType, argTypes, options);
|
|
204
|
+
this._cache.set(cacheKey, fn);
|
|
179
205
|
}
|
|
206
|
+
return fn;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Controllo del risultato prima di errcheck (Python: `_check_retval_` del
|
|
211
|
+
* restype, es. HRESULT in OleDLL). undefined se non c'è.
|
|
212
|
+
* @protected
|
|
213
|
+
*/
|
|
214
|
+
_resultCheck(_returnType, _name) {
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
180
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Crea una nuova funzione, senza cache (vedi func()).
|
|
220
|
+
* @protected
|
|
221
|
+
*/
|
|
222
|
+
_createFunction(name, returnType, argTypes = [], options = {}) {
|
|
181
223
|
// Propagate library-level use_last_error / use_errno to the FFIFunction
|
|
182
224
|
const mergedOptions = {
|
|
183
225
|
...options,
|
|
184
226
|
...(this._use_last_error ? { use_last_error: true } : {}),
|
|
185
227
|
...(this._use_errno ? { use_errno: true } : {}),
|
|
228
|
+
...(structResult(returnType) ? { struct_buffer: true } : {}),
|
|
186
229
|
};
|
|
187
230
|
const ffiFunc = this._lib.func(name, _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), mergedOptions);
|
|
188
231
|
|
|
@@ -193,30 +236,6 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
193
236
|
|
|
194
237
|
const argCount = argTypes.length;
|
|
195
238
|
|
|
196
|
-
// Check if any argtype defines a `from_param` classmethod. When true,
|
|
197
|
-
// every call-site must route through a preprocessing pass that lets
|
|
198
|
-
// user-defined types convert incoming values. This mirrors Python
|
|
199
|
-
// ctypes' from_param protocol.
|
|
200
|
-
const anyFromParam = argTypes.some((t) => t && typeof t === "function" && typeof t.from_param === "function");
|
|
201
|
-
|
|
202
|
-
// Helper: apply Python ctypes _as_parameter_ / from_param protocols.
|
|
203
|
-
// Used only in the slow path (anyFromParam = true).
|
|
204
|
-
const applyParamProtocols = (arg, i) => {
|
|
205
|
-
if (arg && typeof arg === "object" && arg._as_parameter_ !== undefined) {
|
|
206
|
-
arg = arg._as_parameter_;
|
|
207
|
-
}
|
|
208
|
-
if (i < argCount) {
|
|
209
|
-
const t = argTypes[i];
|
|
210
|
-
if (t && typeof t === "function" && typeof t.from_param === "function") {
|
|
211
|
-
arg = t.from_param(arg);
|
|
212
|
-
if (arg && typeof arg === "object" && arg._as_parameter_ !== undefined) {
|
|
213
|
-
arg = arg._as_parameter_;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
return arg;
|
|
218
|
-
};
|
|
219
|
-
|
|
220
239
|
// Conversione degli argomenti come il from_param di base di Python
|
|
221
240
|
// (vedi conversions.js): un convertitore per posizione dichiarata.
|
|
222
241
|
const C = argumentConverters(argTypes, native);
|
|
@@ -226,16 +245,6 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
226
245
|
// Funzioni specializzate per numero di argomenti (niente array per la
|
|
227
246
|
// chiamata comune); `method` è "call" o "callAsync".
|
|
228
247
|
const specialize = (method) => {
|
|
229
|
-
if (anyFromParam) {
|
|
230
|
-
// SLOW PATH: from_param su ogni argomento dichiarato.
|
|
231
|
-
return function (...args) {
|
|
232
|
-
const processedArgs = new Array(args.length);
|
|
233
|
-
for (let i = 0; i < args.length; i++) {
|
|
234
|
-
processedArgs[i] = i < argCount ? applyParamProtocols(C[i](args[i]), i) : coerceValue(args[i]);
|
|
235
|
-
}
|
|
236
|
-
return ffiFunc[method](...processedArgs);
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
248
|
switch (argCount) {
|
|
240
249
|
case 0:
|
|
241
250
|
return function () {
|
|
@@ -278,14 +287,16 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
278
287
|
// Python: con restype POINTER(T) / CFUNCTYPE il risultato è un oggetto
|
|
279
288
|
// puntatore / una funzione, ed errcheck riceve il valore già convertito:
|
|
280
289
|
// in questo caso errcheck è applicato qui invece che nel nativo.
|
|
281
|
-
const
|
|
290
|
+
const baseConvert = resultConverter(returnType);
|
|
291
|
+
const check = this._resultCheck(returnType, name);
|
|
292
|
+
const convertResult = check === undefined ? baseConvert : baseConvert === undefined ? check : (result) => check(baseConvert(result));
|
|
282
293
|
let jsErrcheck = null;
|
|
283
294
|
if (convertResult !== undefined) {
|
|
284
295
|
const rawCall = callMethod;
|
|
285
296
|
const rawAsync = asyncCallMethod;
|
|
286
297
|
const finish = (result, args) => {
|
|
287
298
|
const converted = convertResult(result);
|
|
288
|
-
return jsErrcheck === null ? converted : jsErrcheck(converted,
|
|
299
|
+
return jsErrcheck === null ? converted : jsErrcheck(converted, errcheckFunc(), args);
|
|
289
300
|
};
|
|
290
301
|
callMethod = function (...args) {
|
|
291
302
|
return finish(rawCall.apply(this, args), args);
|
|
@@ -311,6 +322,10 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
311
322
|
};
|
|
312
323
|
}
|
|
313
324
|
|
|
325
|
+
// Python: errcheck riceve la funzione su cui è impostato (l'attributo
|
|
326
|
+
// della libreria, se passa da lì), qualunque sia il restype.
|
|
327
|
+
const errcheckFunc = () => callMethod[kErrcheckFunc] ?? callMethod;
|
|
328
|
+
|
|
314
329
|
// Aggiungi metadata come proprietà non-enumerable per non interferire
|
|
315
330
|
Object.defineProperties(callMethod, {
|
|
316
331
|
funcName: { value: name },
|
|
@@ -323,11 +338,12 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
323
338
|
return ffiFunc._errcheck ?? null;
|
|
324
339
|
},
|
|
325
340
|
set(callback) {
|
|
341
|
+
callback = callback ?? null;
|
|
326
342
|
ffiFunc._errcheck = callback;
|
|
327
343
|
if (convertResult !== undefined) {
|
|
328
|
-
jsErrcheck = callback
|
|
344
|
+
jsErrcheck = callback;
|
|
329
345
|
} else {
|
|
330
|
-
ffiFunc.setErrcheck(callback);
|
|
346
|
+
ffiFunc.setErrcheck(callback === null ? null : (result, _native, args) => callback(result, errcheckFunc(), args));
|
|
331
347
|
}
|
|
332
348
|
},
|
|
333
349
|
enumerable: false,
|
|
@@ -335,7 +351,6 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
335
351
|
},
|
|
336
352
|
});
|
|
337
353
|
|
|
338
|
-
this._cache.set(cacheKey, callMethod);
|
|
339
354
|
return callMethod;
|
|
340
355
|
}
|
|
341
356
|
|
|
@@ -356,7 +371,7 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
356
371
|
* @returns {Object} Oggetto callback con proprietà pointer e metodi
|
|
357
372
|
*/
|
|
358
373
|
callback(fn, returnType, argTypes = []) {
|
|
359
|
-
return this._lib.callback(_toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), adaptCallbackFunction(fn, argTypes));
|
|
374
|
+
return this._lib.callback(_toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native), adaptCallbackFunction(fn, argTypes, returnType, native));
|
|
360
375
|
}
|
|
361
376
|
|
|
362
377
|
/**
|
|
@@ -403,8 +418,8 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
403
418
|
* WinDLL - come CDLL ma con stdcall di default (per Windows)
|
|
404
419
|
*/
|
|
405
420
|
class WinDLL extends CDLL {
|
|
406
|
-
|
|
407
|
-
return super.
|
|
421
|
+
_createFunction(name, returnType, argTypes = [], options = {}) {
|
|
422
|
+
return super._createFunction(name, returnType, argTypes, {
|
|
408
423
|
abi: "stdcall",
|
|
409
424
|
...options,
|
|
410
425
|
});
|
|
@@ -412,33 +427,28 @@ export function createLibraryClasses(Library, LRUCache, _toNativeType, _toNative
|
|
|
412
427
|
}
|
|
413
428
|
|
|
414
429
|
/**
|
|
415
|
-
* OleDLL - come WinDLL ma
|
|
416
|
-
*
|
|
430
|
+
* OleDLL - come WinDLL ma con restype HRESULT un valore negativo (codice di
|
|
431
|
+
* errore HRESULT) lancia un errore.
|
|
417
432
|
*
|
|
418
|
-
* Python ctypes parity: `ctypes.OleDLL
|
|
433
|
+
* Python ctypes parity: `ctypes.OleDLL`; come HRESULT._check_retval_ il
|
|
434
|
+
* controllo precede errcheck e non viene sostituito da esso.
|
|
419
435
|
*/
|
|
420
436
|
class OleDLL extends WinDLL {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
// If the return type is tagged as HRESULT, install an errcheck that
|
|
425
|
-
// throws on negative values (Python's OleDLL behavior).
|
|
426
|
-
if (returnType && returnType._isHResult) {
|
|
427
|
-
const prevErrcheck = fn.errcheck;
|
|
428
|
-
fn.errcheck = (result, func, args) => {
|
|
429
|
-
const r = prevErrcheck ? prevErrcheck(result, func, args) : result;
|
|
430
|
-
const n = typeof r === "bigint" ? Number(r) : r;
|
|
431
|
-
if (typeof n === "number" && n < 0) {
|
|
432
|
-
const hex = (n >>> 0).toString(16).padStart(8, "0").toUpperCase();
|
|
433
|
-
const err = new Error(`OleDLL '${name}' failed with HRESULT 0x${hex}`);
|
|
434
|
-
err.hresult = n;
|
|
435
|
-
err.winerror = n >>> 0;
|
|
436
|
-
throw err;
|
|
437
|
-
}
|
|
438
|
-
return r;
|
|
439
|
-
};
|
|
437
|
+
_resultCheck(returnType, name) {
|
|
438
|
+
if (!returnType || !returnType._isHResult) {
|
|
439
|
+
return undefined;
|
|
440
440
|
}
|
|
441
|
-
return
|
|
441
|
+
return (result) => {
|
|
442
|
+
const n = typeof result === "bigint" ? Number(result) : result;
|
|
443
|
+
if (typeof n === "number" && n < 0) {
|
|
444
|
+
const hex = (n >>> 0).toString(16).padStart(8, "0").toUpperCase();
|
|
445
|
+
const err = new Error(`OleDLL '${name}' failed with HRESULT 0x${hex}`);
|
|
446
|
+
err.hresult = n;
|
|
447
|
+
err.winerror = n >>> 0;
|
|
448
|
+
throw err;
|
|
449
|
+
}
|
|
450
|
+
return result;
|
|
451
|
+
};
|
|
442
452
|
}
|
|
443
453
|
}
|
|
444
454
|
|
package/lib/core/callback.js
CHANGED
|
@@ -12,17 +12,14 @@
|
|
|
12
12
|
*
|
|
13
13
|
* @example Main-thread callback (fast)
|
|
14
14
|
* ```javascript
|
|
15
|
-
* import { callback, c_int } from 'node-ctypes';
|
|
15
|
+
* import { callback, c_int, POINTER } from 'node-ctypes';
|
|
16
16
|
*
|
|
17
|
-
* // Comparison function for qsort
|
|
17
|
+
* // Comparison function for qsort: POINTER(c_int) arguments are pointers
|
|
18
|
+
* // (c_void_p arguments arrive as addresses, bigint).
|
|
18
19
|
* const compareInts = callback(
|
|
19
|
-
* (a, b) =>
|
|
20
|
-
* const aVal = a.readInt32LE(0);
|
|
21
|
-
* const bVal = b.readInt32LE(0);
|
|
22
|
-
* return aVal - bVal;
|
|
23
|
-
* },
|
|
20
|
+
* (a, b) => a[0] - b[0],
|
|
24
21
|
* c_int, // return type
|
|
25
|
-
* [
|
|
22
|
+
* [POINTER(c_int), POINTER(c_int)] // arg types
|
|
26
23
|
* );
|
|
27
24
|
*
|
|
28
25
|
* // Use callback.pointer to pass to C
|
|
@@ -99,19 +96,15 @@ import { trackCallback } from "./callback-tracker.js";
|
|
|
99
96
|
*
|
|
100
97
|
* @example Basic callback usage
|
|
101
98
|
* ```javascript
|
|
102
|
-
* import { CDLL, callback, c_int,
|
|
99
|
+
* import { CDLL, callback, c_int, POINTER } from 'node-ctypes';
|
|
103
100
|
*
|
|
104
101
|
* const libc = new CDLL(null);
|
|
105
102
|
*
|
|
106
103
|
* // Create callback for qsort comparison
|
|
107
104
|
* const compare = callback(
|
|
108
|
-
* (aPtr, bPtr) =>
|
|
109
|
-
* const a = aPtr.readInt32LE(0);
|
|
110
|
-
* const b = bPtr.readInt32LE(0);
|
|
111
|
-
* return a - b;
|
|
112
|
-
* },
|
|
105
|
+
* (aPtr, bPtr) => aPtr.contents.value - bPtr.contents.value,
|
|
113
106
|
* c_int,
|
|
114
|
-
* [
|
|
107
|
+
* [POINTER(c_int), POINTER(c_int)]
|
|
115
108
|
* );
|
|
116
109
|
*
|
|
117
110
|
* // Sort array of integers
|
|
@@ -153,7 +146,7 @@ import { trackCallback } from "./callback-tracker.js";
|
|
|
153
146
|
* @see {@link threadSafeCallback} for thread-safe callbacks
|
|
154
147
|
*/
|
|
155
148
|
export function callback(fn, returnType, argTypes = [], native, abi = undefined) {
|
|
156
|
-
const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
|
|
149
|
+
const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
|
|
157
150
|
if (abi) args.push(abi);
|
|
158
151
|
const cb = new native.Callback(...args);
|
|
159
152
|
|
|
@@ -282,7 +275,7 @@ export function callback(fn, returnType, argTypes = [], native, abi = undefined)
|
|
|
282
275
|
* @see {@link callback} for main-thread-only callbacks
|
|
283
276
|
*/
|
|
284
277
|
export function threadSafeCallback(fn, returnType, argTypes = [], native, abi = undefined) {
|
|
285
|
-
const args = [adaptCallbackFunction(fn, argTypes), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
|
|
278
|
+
const args = [adaptCallbackFunction(fn, argTypes, returnType, native), _toNativeReturnType(returnType, native), _toNativeTypes(argTypes, native)];
|
|
286
279
|
if (abi) args.push(abi);
|
|
287
280
|
const cb = new native.ThreadSafeCallback(...args);
|
|
288
281
|
|