node-ctypes 2.3.0 → 2.5.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/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.0.0"
137
+ * console.log(Version.toString()); // "2.5.0"
138
138
  * ```
139
139
  *
140
140
  * @category Library Loading
@@ -173,16 +173,19 @@ export class Library {
173
173
  symbol(name: string): bigint;
174
174
 
175
175
  /**
176
- * Close the library and release resources. Functions obtained from it
176
+ * Logically close the library. Functions obtained from it
177
177
  * throw when called afterwards. Throws while a call to one of its
178
178
  * functions is in progress (from a callback, or a pending `callAsync()`).
179
+ * Existing `in_dll()` views and dependent memory remain valid and defer
180
+ * native handle release until their last owner is collected.
181
+ * Physical unloading depends on the OS loader; musl keeps modules resident.
179
182
  */
180
183
  close(): void;
181
184
 
182
185
  /** Library file path. */
183
186
  readonly path: string;
184
187
 
185
- /** Whether the library is currently loaded. */
188
+ /** Whether the logical library handle is open (not a physical-unload probe). */
186
189
  readonly loaded: boolean;
187
190
  }
188
191
 
@@ -225,6 +228,7 @@ export interface FFIFunction {
225
228
 
226
229
  /** The function address as BigInt. */
227
230
  readonly address: bigint;
231
+ readonly _as_parameter_: bigint;
228
232
 
229
233
  /**
230
234
  * Error checking callback, called after every invocation (`null` when not set).
@@ -248,8 +252,8 @@ export interface NativeFFIFunction<TArgs extends readonly FFIType[] = FFIType[],
248
252
  /** Call the native function asynchronously on a worker thread. */
249
253
  callAsync(...args: FFIArgs<TArgs>): Promise<FFIReturn<TRet>>;
250
254
 
251
- /** Set (or clear with `null`) the error checking callback. */
252
- setErrcheck(callback: ErrcheckCallback | null): void;
255
+ /** Set (or clear with `null`) the hook captured at each call's entry, including async calls. */
256
+ setErrcheck(callback: NativeErrcheckCallback<TArgs, TRet> | null): void;
253
257
 
254
258
  /** `GetLastError()` (Windows) or `errno` captured after the last call, with `use_last_error`. */
255
259
  getCapturedLastError(): number;
@@ -264,6 +268,13 @@ export interface NativeFFIFunction<TArgs extends readonly FFIType[] = FFIType[],
264
268
  readonly address: bigint;
265
269
  }
266
270
 
271
+ /**
272
+ * Low-level errcheck: `func` is the native handle, invoked with `.call()`,
273
+ * not a directly callable JavaScript function.
274
+ * @category Library Loading
275
+ */
276
+ export type NativeErrcheckCallback<TArgs extends readonly FFIType[] = FFIType[], TRet extends FFIType | null = FFIType> = (result: any, func: NativeFFIFunction<TArgs, TRet>, args: any[]) => any;
277
+
267
278
  /**
268
279
  * Strongly-typed FFI function returned by `CDLL.func` when the
269
280
  * argument types and return type are given as a literal tuple and constant respectively.
@@ -278,6 +289,7 @@ export interface TypedFFIFunction<TArgs extends readonly FFIType[], TRet extends
278
289
  callAsync(...args: FFIArgs<TArgs>): Promise<FFIReturn<TRet>>;
279
290
  readonly funcName: string;
280
291
  readonly address: bigint;
292
+ readonly _as_parameter_: bigint;
281
293
  errcheck: ErrcheckCallback | null;
282
294
  }
283
295
 
@@ -374,6 +386,7 @@ export class CDLL {
374
386
  */
375
387
  /** Typed overload: narrows args/return when argTypes is a literal tuple. */
376
388
  func<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(name: string, returnType: TRet, argTypes: TArgs, options?: FunctionOptions): TypedFFIFunction<TArgs, TRet>;
389
+ func(name: string): TypedFFIFunction<readonly FFIType[], typeof c_int32>;
377
390
  func(name: string, returnType: FFIType | null, argTypes?: FFIType[], options?: FunctionOptions): FFIFunction;
378
391
 
379
392
  /**
@@ -387,6 +400,9 @@ export class CDLL {
387
400
  * Close the library and clear the function cache. Functions obtained from
388
401
  * it throw when called afterwards. Throws while a call to one of its
389
402
  * functions is in progress (from a callback, or a pending `callAsync()`).
403
+ * Existing `in_dll()` views defer native handle release until their dependent
404
+ * memory is collected, but new calls and symbol lookups are rejected.
405
+ * Physical unloading depends on the OS loader; musl keeps modules resident.
390
406
  */
391
407
  close(): void;
392
408
 
@@ -397,7 +413,7 @@ export class CDLL {
397
413
  * Create a native callback bound to this library's context.
398
414
  * Call `release()` when it is no longer needed.
399
415
  */
400
- callback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): Callback;
416
+ callback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>, returnType: TRet, argTypes?: TArgs): Callback;
401
417
 
402
418
  /**
403
419
  * Read the snapshotted `GetLastError()` (Windows) or `errno` from the most
@@ -419,7 +435,7 @@ export class CDLL {
419
435
  /** Library file path. */
420
436
  readonly path: string;
421
437
 
422
- /** Whether the library is loaded. */
438
+ /** Whether the logical handle is open, independently of physical module residency. */
423
439
  readonly loaded: boolean;
424
440
 
425
441
  /**
@@ -506,8 +522,8 @@ export class OleDLL extends WinDLL {
506
522
  }
507
523
 
508
524
  /**
509
- * `HRESULT` return type marker. Use as `restype` on an OleDLL function to
510
- * enable automatic throw-on-failure behavior.
525
+ * `HRESULT` return type marker. Explicit use as restype enables failure checks
526
+ * for all library loaders and prototype callers, before errcheck.
511
527
  *
512
528
  * Python equivalent: `ctypes.HRESULT`
513
529
  *
@@ -592,6 +608,7 @@ export const oledll: LibraryNamespace<OleDLL> | undefined;
592
608
  * @category Callbacks
593
609
  */
594
610
  export interface CallbackWrapper {
611
+ readonly _callback: Callback;
595
612
  /** The callback function pointer, passable to native functions. */
596
613
  readonly pointer: bigint;
597
614
 
@@ -610,6 +627,7 @@ export interface CallbackWrapper {
610
627
  * @category Callbacks
611
628
  */
612
629
  export interface ThreadSafeCallbackWrapper extends CallbackWrapper {
630
+ readonly _callback: ThreadSafeCallback;
613
631
  /** Keep the Node.js event loop alive until released (the default). */
614
632
  ref(): this;
615
633
 
@@ -620,6 +638,12 @@ export interface ThreadSafeCallbackWrapper extends CallbackWrapper {
620
638
  unref(): this;
621
639
  }
622
640
 
641
+ /**
642
+ * A CFUNCTYPE/WINFUNCTYPE callback that is also a typed native caller.
643
+ * @category Callbacks
644
+ */
645
+ export type CallableCallback<TArgs extends readonly FFIType[], TRet extends FFIType | null> = TypedFFIFunction<TArgs, TRet> & CallbackWrapper;
646
+
623
647
  /**
624
648
  * Native callback class for main-thread callbacks.
625
649
  * @category Callbacks
@@ -628,10 +652,8 @@ export class Callback {
628
652
  constructor(fn: Function, returnType: AnyType, argTypes?: AnyType[]);
629
653
  /** The callback function pointer, passable to native functions. */
630
654
  readonly pointer: bigint;
631
- /** Same as {@link Callback.pointer}. */
655
+ /** Return the function pointer, throwing if the callback has been released. */
632
656
  getPointer(): bigint;
633
- /** Same as `pointer`: lets the callback be passed directly as an argument. */
634
- readonly _as_parameter_: bigint;
635
657
  /** Release the callback and free native resources. Must be called when done. */
636
658
  release(): void;
637
659
  /**
@@ -731,7 +753,11 @@ export type FieldSpec = AnyType | StructDef | ArrayTypeDef | BitFieldDef | Anony
731
753
  */
732
754
  export type JsFromCType<T> =
733
755
  T extends SimpleCDataConstructor<infer Tag>
734
- ? JsFromTag<Tag>
756
+ ? T extends { prototype: infer Instance }
757
+ ? IsAny<Instance> extends true
758
+ ? JsFromTag<Tag>
759
+ : Instance
760
+ : JsFromTag<Tag>
735
761
  : T extends BitFieldDef
736
762
  ? number
737
763
  : T extends PointerTypeDef<infer B>
@@ -789,10 +815,10 @@ type FieldValue<F extends Record<string, FieldSpec>, K extends keyof F> = string
789
815
  type FieldArg<F extends Record<string, FieldSpec>, K extends keyof F> = string extends keyof F ? any : JsArgFromCType<F[K]>;
790
816
 
791
817
  /**
792
- * Element read from an array of `E`. Narrowed only to `number`: arrays are
793
- * also Buffers, whose numeric index is `number`, so other element types stay `any`.
818
+ * Numeric elements and scalar subclass instances are typed; other element
819
+ * representations retain the existing permissive array API.
794
820
  */
795
- type ArrayElement<E> = IsAny<E> extends true ? any : JsFromCType<E> extends number ? number : any;
821
+ type ArrayElement<E> = IsAny<E> extends true ? any : JsFromCType<E> extends SimpleCDataInstance<unknown> ? JsFromCType<E> : JsFromCType<E> extends number ? number : any;
796
822
 
797
823
  /** Element accepted when writing an array of `E`. */
798
824
  type ArrayElementArg<E> = IsAny<E> extends true ? any : E extends StructureClass ? Buffer | Record<string, any> : JsArgFromCType<E>;
@@ -801,7 +827,18 @@ type ArrayElementArg<E> = IsAny<E> extends true ? any : E extends StructureClass
801
827
  type PointerValue<T> = IsAny<T> extends true ? any : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
802
828
 
803
829
  /** `p.contents`: a live instance on the pointed memory (Python parity). */
804
- type PointerContents<T> = IsAny<T> extends true ? any : T extends SimpleCDataConstructor<infer Tag> ? SimpleCDataInstance<JsFromTag<Tag>> : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
830
+ type PointerContents<T> =
831
+ IsAny<T> extends true
832
+ ? any
833
+ : T extends SimpleCDataConstructor<infer Tag>
834
+ ? T extends { prototype: infer Instance }
835
+ ? IsAny<Instance> extends true
836
+ ? SimpleCDataInstance<JsFromTag<Tag>>
837
+ : Instance
838
+ : SimpleCDataInstance<JsFromTag<Tag>>
839
+ : T extends StructureClass
840
+ ? InstanceType<T>
841
+ : JsFromCType<T>;
805
842
 
806
843
  /** `string` for `c_char`/`c_wchar` arrays (read as text, as Python), otherwise `Else`. */
807
844
  type CharArrayValue<E, Else> = IsAny<E> extends true ? Else : [E] extends [SimpleCDataConstructor<"char">] ? string : [E] extends [SimpleCDataConstructor<"wchar">] ? string : Else;
@@ -812,7 +849,7 @@ type CharArrayValue<E, Else> = IsAny<E> extends true ? Else : [E] extends [Simpl
812
849
  * `c_char` arrays also expose `.value`/`.raw` and `c_wchar` arrays `.value`.
813
850
  * @category Structures
814
851
  */
815
- export type ArrayInstance<E = any> = Omit<Buffer, ElementMethod | "length" | "toJSON"> &
852
+ export type ArrayInstance<E = any> = Omit<Buffer, ElementMethod | "length" | "toJSON" | number> &
816
853
  (IsAny<E> extends true
817
854
  ? ArrayProxy<any>
818
855
  : [E] extends [SimpleCDataConstructor<"char">]
@@ -857,7 +894,8 @@ type ArgsFromCTypes<TArgs extends readonly any[]> = {
857
894
  };
858
895
 
859
896
  /** JS argument accepted for a function parameter of type `T`. */
860
- type JsArgFromFFIType<T> = T extends StructureClass ? Buffer | { _buffer: Buffer } | Record<string, any> : T extends ArrayTypeDef<infer E> ? ArrayInstance<E> | ArrayBufferView | ArrayBuffer | { readonly _as_parameter_: unknown } : JsArgFromCType<T>;
897
+ type JsArgFromFFIType<T> =
898
+ { readonly _as_parameter_: unknown } | (T extends StructureClass ? Buffer | { _buffer: Buffer } | Record<string, any> : T extends ArrayTypeDef<infer E> ? ArrayInstance<E> | ArrayBufferView | ArrayBuffer : JsArgFromCType<T>);
861
899
 
862
900
  /** Function arguments for `argtypes` `TArgs` (`any[]` when not a literal tuple). */
863
901
  type FFIArgs<TArgs extends readonly any[]> = FFIType[] extends TArgs ? any[] : { [K in keyof TArgs]: JsArgFromFFIType<TArgs[K]> };
@@ -868,7 +906,7 @@ type FFIArgs<TArgs extends readonly any[]> = FFIType[] extends TArgs ? any[] : {
868
906
  * restype a callable function (`null` for NULL) and a Structure/Union class an
869
907
  * instance of that class.
870
908
  */
871
- type FFIReturn<T> = FFIType extends T ? any : T extends null ? undefined : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
909
+ type FFIReturn<T> = FFIType extends T ? any : T extends null ? undefined : T extends { _check_retval_: (...args: never[]) => infer Result } ? Result : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
872
910
 
873
911
  /**
874
912
  * A union type definition created by the {@link union} function.
@@ -1022,7 +1060,7 @@ export interface StructOptions {
1022
1060
  /** If `true`, disables padding between fields (as `pack: 1`). */
1023
1061
  packed?: boolean;
1024
1062
  /** Maximum field alignment in bytes, as Python's `_pack_`. */
1025
- pack?: number;
1063
+ pack?: number | boolean | bigint | string | null;
1026
1064
  /** Bit field layout, as Python's `_layout_` (`"ms"` with `pack`, otherwise the platform's). */
1027
1065
  layout?: "gcc-sysv" | "ms";
1028
1066
  /** Minimum alignment in bytes, as Python's `_align_`. */
@@ -1165,8 +1203,10 @@ export interface PointerInstance<T = any> {
1165
1203
  * @category Pointers
1166
1204
  */
1167
1205
  export interface PointerTypeDef<T = any> {
1168
- /** The type this pointer points to. */
1169
- readonly _pointerTo: AnyType | StructDef | StructureClass | PointerTypeDef;
1206
+ /** The resolved base type, including for lazy pointer declarations. */
1207
+ readonly _pointerTo: T;
1208
+ /** Python ctypes alias for the resolved base type. */
1209
+ readonly _type_: T;
1170
1210
  /** Size of the pointed-to type. */
1171
1211
  readonly _baseSize: number;
1172
1212
  /** Pointer size (always 8 on 64-bit). */
@@ -1238,23 +1278,32 @@ export interface PointerTypeDef<T = any> {
1238
1278
 
1239
1279
  /**
1240
1280
  * Low-level native struct type. Prefer {@link Structure} for most use cases.
1281
+ * Mutable only until captured by a field, array, prepared function/callback
1282
+ * signature or native value. Finalization includes nested descriptors.
1283
+ * Create a new descriptor rather than modifying a finalized layout.
1241
1284
  * @category Structures
1242
1285
  */
1243
1286
  export class StructType {
1244
- constructor(isUnion?: boolean);
1245
- addField(name: string, type: AnyType | StructType | ArrayType): this;
1287
+ constructor(options?: { union?: boolean; alignment?: number; memoryClass?: boolean });
1288
+ /** Append a field while the builder is open; throws after finalization. */
1289
+ addField(name: string, type: number | StructType | ArrayType | { readonly _native: ArrayType }, options?: { anonymous?: boolean }): this;
1290
+ /** Query without finalizing an unused builder. */
1246
1291
  getSize(): number;
1292
+ /** Query without finalizing an unused builder. */
1247
1293
  getAlignment(): number;
1248
- create(values?: Record<string, any>): Buffer;
1294
+ /** Materialize a value and finalize its layout. */
1295
+ create(values?: Record<string, unknown>): Record<string, unknown> & { readonly _buffer: Buffer };
1249
1296
  read(buffer: Buffer): Record<string, any>;
1297
+ toObject(source: Buffer | { readonly _buffer: Buffer }): Record<string, unknown>;
1250
1298
  }
1251
1299
 
1252
1300
  /**
1253
1301
  * Low-level native array type. Prefer {@link array} for most use cases.
1302
+ * Captures and finalizes an aggregate element's layout, including at length zero.
1254
1303
  * @category Structures
1255
1304
  */
1256
1305
  export class ArrayType {
1257
- constructor(elementType: AnyType, count: number);
1306
+ constructor(elementType: number | StructType, count: number);
1258
1307
  getSize(): number;
1259
1308
  getLength(): number;
1260
1309
  getAlignment(): number;
@@ -1313,7 +1362,7 @@ export class Structure<F extends Record<string, FieldSpec> = Record<string, any>
1313
1362
  * Maximum field alignment in bytes, as Python's `_pack_` (`1` = no padding).
1314
1363
  * `true` is accepted as `1`.
1315
1364
  */
1316
- static _pack_?: number | boolean;
1365
+ static _pack_?: number | boolean | bigint | string | null;
1317
1366
 
1318
1367
  /**
1319
1368
  * Bit field layout, as Python's `_layout_`: `"gcc-sysv"` (default except on
@@ -1525,7 +1574,11 @@ export function load(path: string | null): Library;
1525
1574
  *
1526
1575
  * @category Callbacks
1527
1576
  */
1528
- export function callback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): CallbackWrapper;
1577
+ type CallbackRestype = SimpleCDataConstructor | PointerTypeDef | FuncPtrFactory | number | null;
1578
+ type CallbackArgs<T extends readonly FFIType[]> = { -readonly [K in keyof T]: JsFromCType<T[K]> };
1579
+ type CallbackResult<T> = T extends null | SimpleCDataConstructor<"void"> ? void : T extends StructureClass | StructDef | ArrayTypeDef ? never : JsArgFromCType<T> | (T extends SimpleCDataConstructor ? InstanceType<T> : never);
1580
+
1581
+ export function callback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>, returnType: TRet, argTypes?: TArgs): CallbackWrapper;
1529
1582
 
1530
1583
  /**
1531
1584
  * Create a thread-safe callback that can be invoked from any thread.
@@ -1540,7 +1593,7 @@ export function callback(fn: Function, returnType: AnyType | null, argTypes?: An
1540
1593
  *
1541
1594
  * @category Callbacks
1542
1595
  */
1543
- export function threadSafeCallback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): ThreadSafeCallbackWrapper;
1596
+ export function threadSafeCallback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>, returnType: TRet, argTypes?: TArgs): ThreadSafeCallbackWrapper;
1544
1597
 
1545
1598
  /**
1546
1599
  * Create a function pointer type with cdecl calling convention.
@@ -1577,8 +1630,8 @@ export function threadSafeCallback(fn: Function, returnType: AnyType | null, arg
1577
1630
  * @category Function Pointers
1578
1631
  */
1579
1632
  export interface ParamFlag {
1580
- /** `"in"` for input params (default), `"out"` for output params (POINTER(T) argtype). */
1581
- dir: "in" | "out";
1633
+ /** OUT allocates a pointee; INOUT uses and returns the supplied instance. */
1634
+ dir: "in" | "out" | "inout";
1582
1635
  /** Parameter name, used for the named-call form `fn({ name: value, ... })`. */
1583
1636
  name: string;
1584
1637
  /** Optional default value; applied when the caller omits this `in` param. */
@@ -1590,47 +1643,54 @@ export interface ParamFlag {
1590
1643
  *
1591
1644
  * @category Function Pointers
1592
1645
  */
1593
- export interface FuncPtrFactory {
1646
+ export interface FuncPtrFactory<TRet extends FFIType | null = FFIType | null, TArgs extends readonly FFIType[] = readonly FFIType[]> {
1594
1647
  /** Call with a raw address to produce a caller. */
1595
- (address: bigint | number): (...args: any[]) => any;
1648
+ (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
1649
+ new (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
1596
1650
  /**
1597
- * Call with a JS function to produce a C-callable callback closure, usable
1598
- * as argument or struct field of this type. Keep it referenced while C may
1651
+ * Call with a JS function to produce a directly callable, typed C callback,
1652
+ * usable as an argument or struct field. Keep it referenced while C may
1599
1653
  * call it; `release()` frees it.
1600
1654
  */
1601
- (fn: (...args: any[]) => any): { readonly pointer: bigint; readonly _as_parameter_: bigint; release(): void };
1655
+ (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
1656
+ new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallableCallback<TArgs, TRet>;
1602
1657
  /**
1603
1658
  * Bind an exported function of a library, optionally with paramflags.
1604
1659
  * Python: `prototype((name, dll))` / `prototype((name, dll), paramflags)`.
1605
1660
  */
1606
- (spec: readonly [name: string, library: CDLL], paramflags?: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1661
+ (spec: readonly [name: string, library: CDLL]): TypedFFIFunction<TArgs, TRet>;
1662
+ (spec: readonly [name: string, library: CDLL], paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): FFIFunction;
1607
1663
 
1664
+ /** Shared metadata; assigning it does not recompile the captured signature. */
1608
1665
  restype: FFIType | null;
1666
+ /** Shared metadata; mutating it does not recompile the captured signature. */
1609
1667
  argtypes: FFIType[];
1610
1668
  readonly _isFuncPtr: true;
1611
1669
 
1612
1670
  /**
1613
1671
  * Bind the factory to a library export with Python-style paramflags.
1614
- * Out params are allocated automatically and returned as part of the tuple.
1672
+ * Out params are allocated automatically and returned alone (one value or
1673
+ * an array). Returning the original `args` from errcheck keeps this behavior.
1674
+ * `callAsync()` uses the same output processing and per-call hook snapshot.
1615
1675
  *
1616
1676
  * Python ctypes parity: `prototype((name, lib), paramflags)`.
1617
1677
  *
1618
1678
  * @example
1619
1679
  * ```javascript
1620
- * const proto = WINFUNCTYPE(BOOL, HWND, POINTER(DWORD), POINTER(DWORD));
1680
+ * const proto = WINFUNCTYPE(DWORD, HWND, LPDWORD);
1621
1681
  * const fn = proto.bind(user32, "GetWindowThreadProcessId", [
1622
1682
  * { dir: "in", name: "hWnd" },
1623
1683
  * { dir: "out", name: "pid" },
1624
- * { dir: "out", name: "tid" },
1625
1684
  * ]);
1626
- * const [ok, pid, tid] = fn(hwnd); // positional
1627
- * const [ok2, pid2, tid2] = fn({ hWnd: hwnd }); // named
1685
+ * const pid = fn(hwnd); // positional; thread ID is discarded
1686
+ * const pid2 = fn({ hWnd: hwnd }); // named
1687
+ * const pid3 = await fn.callAsync(hwnd); // async, same output processing
1628
1688
  * ```
1629
1689
  */
1630
- bind(library: CDLL, symbolName: string, paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1690
+ bind(library: CDLL, symbolName: string, paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): FFIFunction;
1631
1691
  }
1632
1692
 
1633
- export function CFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1693
+ export function CFUNCTYPE<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(restype: TRet, ...argtypes: TArgs): FuncPtrFactory<TRet, TArgs>;
1634
1694
 
1635
1695
  /**
1636
1696
  * Create a function pointer type with stdcall calling convention (Windows).
@@ -1645,7 +1705,7 @@ export function CFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): Func
1645
1705
  *
1646
1706
  * @category Callbacks
1647
1707
  */
1648
- export function WINFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1708
+ export function WINFUNCTYPE<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(restype: TRet, ...argtypes: TArgs): FuncPtrFactory<TRet, TArgs>;
1649
1709
 
1650
1710
  /**
1651
1711
  * Create a C string buffer (null-terminated).
@@ -1717,14 +1777,14 @@ export function wstring_at(address: Buffer | bigint | number, size?: number): st
1717
1777
  *
1718
1778
  * @category Memory
1719
1779
  */
1720
- export function addressof(ptr: Buffer | bigint | number): bigint;
1780
+ export function addressof(ptr: ArrayBufferView | ArrayBuffer | { readonly _buffer: Buffer } | PointerInstance | bigint | number): bigint;
1721
1781
 
1722
1782
  /**
1723
1783
  * Memory argument of {@link memmove} / {@link memset}: a buffer (any typed
1724
1784
  * array, DataView or ArrayBuffer, as bytes), a ctypes instance, a pointer or an
1725
1785
  * address.
1726
1786
  */
1727
- export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffer: Buffer } | PointerInstance | bigint | number;
1787
+ export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffer: Buffer } | { readonly _as_parameter_: unknown } | PointerInstance | bigint | number | null;
1728
1788
 
1729
1789
  /**
1730
1790
  * Copy memory from source to destination.
@@ -1733,7 +1793,7 @@ export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffe
1733
1793
  *
1734
1794
  * @category Memory
1735
1795
  */
1736
- export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): void;
1796
+ export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): bigint;
1737
1797
 
1738
1798
  /**
1739
1799
  * Fill memory with a byte value.
@@ -1742,7 +1802,7 @@ export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): vo
1742
1802
  *
1743
1803
  * @category Memory
1744
1804
  */
1745
- export function memset(dst: MemoryTarget, value: number, count: number): void;
1805
+ export function memset(dst: MemoryTarget, value: number, count: number): bigint;
1746
1806
 
1747
1807
  /**
1748
1808
  * Read a typed value from a buffer at a given offset.
@@ -1884,6 +1944,10 @@ export interface DefinedClass<F extends Record<string, FieldSpec>, I> {
1884
1944
  /**
1885
1945
  * Define a fixed-size array type.
1886
1946
  *
1947
+ * Weakly interned by element type and count: live types keep their identity,
1948
+ * including when retained by instances, signatures or containing types.
1949
+ * The cache does not keep unused types alive.
1950
+ *
1887
1951
  * Python equivalent: `c_int * 5`
1888
1952
  *
1889
1953
  * @param elementType - Type of each element
@@ -1930,15 +1994,22 @@ export function ARRAY<E extends ArrayElementType>(elementType: E, count: number)
1930
1994
  export function bitfield(baseType: SimpleCDataConstructor, bits: number): BitFieldDef;
1931
1995
 
1932
1996
  /**
1933
- * Pass an object by reference (returns its underlying buffer).
1997
+ * Pass an object by reference, retaining its owner and applying a signed byte offset.
1998
+ * In-range references are Buffer views; out-of-range offsets are address carriers.
1934
1999
  *
1935
2000
  * Python equivalent: `ctypes.byref`
1936
2001
  *
1937
2002
  * @param obj - A Buffer, SimpleCData instance, or any object with a `_buffer` property
2003
+ * @param offset - Signed byte offset; the caller is responsible for valid external memory
1938
2004
  *
1939
2005
  * @category Pointers
1940
2006
  */
1941
- export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }): Buffer;
2007
+ export interface ByRefAddress {
2008
+ readonly address: bigint;
2009
+ readonly _as_parameter_: bigint;
2010
+ }
2011
+ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, offset?: 0): Buffer;
2012
+ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, offset: number): Buffer | ByRefAddress;
1942
2013
 
1943
2014
  /**
1944
2015
  * Interpret a pointer as a different type.
@@ -1948,9 +2019,10 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }):
1948
2019
  * When the target is a {@link PointerTypeDef}, returns a {@link PointerInstance} with
1949
2020
  * `.contents` and `[index]` access — equivalent to Python's
1950
2021
  * `cast(c_void_p(addr), POINTER(MyStruct))`.
2022
+ * A {@link FuncPtrFactory} target returns a caller with that prototype.
1951
2023
  *
1952
- * @param ptr - Buffer, BigInt address, number, or SimpleCData instance (e.g., `c_void_p`)
1953
- * @param targetType - The target type (primitive, struct, or POINTER type)
2024
+ * @param ptr - Memory, a pointer/address, or a native function/callback
2025
+ * @param targetType - The target type (primitive, struct, POINTER or CFUNCTYPE)
1954
2026
  *
1955
2027
  * @example Cast to POINTER for typed array access
1956
2028
  * ```javascript
@@ -1968,8 +2040,11 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }):
1968
2040
  *
1969
2041
  * @category Pointers
1970
2042
  */
1971
- export function cast<T>(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: PointerTypeDef<T>): PointerInstance<T>;
1972
- export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: AnyType | StructDef | StructureClass): any;
2043
+ type CastSource = MemorySource | ArrayBuffer | ByRefAddress | FFIFunction | CallbackWrapper | null;
2044
+ export function cast<T>(ptr: CastSource, targetType: PointerTypeDef<T>): PointerInstance<T>;
2045
+ export function cast<TRet extends FFIType | null, TArgs extends readonly FFIType[]>(ptr: CastSource, targetType: FuncPtrFactory<TRet, TArgs>): TypedFFIFunction<TArgs, TRet>;
2046
+ export function cast<T extends SimpleCDataConstructor<"pointer"> | SimpleCDataConstructor<"string"> | SimpleCDataConstructor<"wstring">>(ptr: CastSource, targetType: T): InstanceType<T>;
2047
+ export function cast(ptr: CastSource, targetType: AnyType | StructDef | StructureClass): any;
1973
2048
 
1974
2049
  /**
1975
2050
  * Create a pointer type for a given base type.
@@ -2028,6 +2103,7 @@ export function POINTER<T extends AnyType | StructureClass>(baseType: () => T):
2028
2103
  *
2029
2104
  * @category Pointers
2030
2105
  */
2106
+ export function pointer<T>(obj: PointerInstance<T>): PointerInstance<PointerTypeDef<T>>;
2031
2107
  export function pointer<T extends Structure<any>>(obj: T): PointerInstance<new (...args: any[]) => T>;
2032
2108
  export function pointer<V>(obj: SimpleCDataInstance<V>): PointerInstance;
2033
2109
  export function pointer(obj: Buffer | { _buffer: Buffer }): PointerInstance;
@@ -2146,13 +2222,13 @@ export interface SimpleCDataConstructor<Tag extends string = string> {
2146
2222
  _writer(buf: Buffer, offset: number, value: JsArgFromTag<Tag>): void;
2147
2223
 
2148
2224
  /** Create an instance that aliases an existing Buffer (zero-copy). */
2149
- from_buffer(buffer: Buffer, offset?: number): SimpleCDataInstance<JsFromTag<Tag>>;
2225
+ from_buffer<T extends SimpleCDataConstructor<Tag>>(this: T, buffer: ArrayBufferView | { readonly _buffer: Buffer }, offset?: number): InstanceType<T>;
2150
2226
  /** Create an instance whose buffer is a copy of the source bytes. */
2151
- from_buffer_copy(buffer: Buffer, offset?: number): SimpleCDataInstance<JsFromTag<Tag>>;
2227
+ from_buffer_copy<T extends SimpleCDataConstructor<Tag>>(this: T, buffer: ArrayBufferView | { readonly _buffer: Buffer }, offset?: number): InstanceType<T>;
2152
2228
  /** Create an instance viewing raw memory at the given address. */
2153
- from_address(address: bigint | number): SimpleCDataInstance<JsFromTag<Tag>>;
2229
+ from_address<T extends SimpleCDataConstructor<Tag>>(this: T, address: bigint | number): InstanceType<T>;
2154
2230
  /** Bind this type to an exported global variable in a shared library. */
2155
- in_dll(library: CDLL | Library, name: string): SimpleCDataInstance<JsFromTag<Tag>>;
2231
+ in_dll<T extends SimpleCDataConstructor<Tag>>(this: T, library: CDLL | Library, name: string): InstanceType<T>;
2156
2232
  }
2157
2233
 
2158
2234
  /**
@@ -2175,7 +2251,7 @@ export type JsFromTag<Tag extends string> = Tag extends "void"
2175
2251
  : Tag extends "wstring"
2176
2252
  ? string | null
2177
2253
  : Tag extends "pointer"
2178
- ? bigint | Buffer | null
2254
+ ? bigint | null
2179
2255
  : any;
2180
2256
 
2181
2257
  /**
@@ -2224,6 +2300,8 @@ export interface SimpleCDataInstance<T = any> {
2224
2300
  toString(): string;
2225
2301
  toJSON(): T;
2226
2302
  valueOf(): T;
2303
+ /** OUT conversion; defaults to the value for builtins and the instance for subclasses. */
2304
+ __ctypes_from_outparam__(): unknown;
2227
2305
  }
2228
2306
 
2229
2307
  // =============================================================================
package/lib/index.js CHANGED
@@ -20,7 +20,7 @@ import path from "node:path";
20
20
  import { fileURLToPath } from "node:url";
21
21
 
22
22
  // Import refactored modules
23
- import { LRUCache } from "./utils/cache.js";
23
+ import { LRUCache, cacheWeakValue } from "./utils/cache.js";
24
24
  import { _initConstants } from "./platform/constants.js";
25
25
  import { _toNativeType, _toNativeTypes } from "./core/types.js";
26
26
  import { createLazyLoader } from "./core/lazy-loader.js";
@@ -42,7 +42,7 @@ import { createMemoryOps } from "./memory/operations.js";
42
42
  import { enableMirrors, wrapNative } from "./memory/mirror.js";
43
43
  import { addressOf as _addressOf, byref as _byref, cast as _cast, ptrToBuffer as _ptrToBuffer, POINTER as _POINTER, pointer as _pointer } from "./memory/pointer.js";
44
44
  import { FormatError as _FormatError, WinError as _WinError, ArgumentError } from "./platform/errors.js";
45
- import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField } from "./structures/helpers/common.js";
45
+ import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField, registerSimpleType } from "./structures/helpers/common.js";
46
46
  import { array as _array } from "./structures/helpers/array.js";
47
47
  import { union as _union } from "./structures/helpers/union.js";
48
48
  import { struct as _struct } from "./structures/helpers/struct.js";
@@ -255,8 +255,8 @@ function addressOf(ptr) {
255
255
  return _addressOf(ptr, alloc, native);
256
256
  }
257
257
 
258
- function byref(obj) {
259
- return _byref(obj);
258
+ function byref(obj, offset = 0) {
259
+ return _byref(obj, offset, native);
260
260
  }
261
261
 
262
262
  function cast(ptr, targetType) {
@@ -359,12 +359,12 @@ memoryDeps.Union = Union;
359
359
  * Helper per creare array a dimensione fissa (come c_int * 5 in Python)
360
360
  * Ritorna un ArrayType wrapper con supporto per indexing arr[i]
361
361
  *
362
- * @param {string} elementType - Tipo degli elementi ('int32', 'float', etc.)
362
+ * @param {Function|Object} elementType - Tipo degli elementi (c_int32, Structure, etc.)
363
363
  * @param {number} count - Numero di elementi
364
364
  * @returns {Object} ArrayType con metodi getSize(), getLength(), create(), wrap()
365
365
  *
366
366
  * @example
367
- * const IntArray5 = array('int32', 5);
367
+ * const IntArray5 = array(c_int32, 5);
368
368
  * const arr = IntArray5.create([1, 2, 3, 4, 5]);
369
369
  * console.log(arr[0]); // 1 - indexing Python-like!
370
370
  * arr[2] = 42;
@@ -373,12 +373,12 @@ memoryDeps.Union = Union;
373
373
  function array(elementType, count) {
374
374
  const cacheable = elementType !== null && (typeof elementType === "object" || typeof elementType === "function");
375
375
  let byCount = cacheable ? arrayTypes.get(elementType) : undefined;
376
- let type = byCount?.get(count);
376
+ let type = byCount?.get(count)?.deref();
377
377
  if (type === undefined) {
378
378
  type = _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p, ptrToBuffer);
379
379
  if (cacheable) {
380
380
  if (byCount === undefined) arrayTypes.set(elementType, (byCount = new Map()));
381
- byCount.set(count, type);
381
+ cacheWeakValue(byCount, count, type);
382
382
  }
383
383
  }
384
384
  return type;
@@ -542,6 +542,8 @@ const wintypes = createWinTypes(primitiveTypes, { Structure, POINTER, array });
542
542
  class HRESULT extends c_int32 {
543
543
  static _isHResult = true;
544
544
  }
545
+ registerSimpleType(HRESULT);
546
+ OleDLL.defaultRestype = HRESULT;
545
547
 
546
548
  // ============================================================================
547
549
  // Alias Python-compatibili per Memory Management