node-ctypes 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.4.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
 
@@ -628,10 +646,8 @@ export class Callback {
628
646
  constructor(fn: Function, returnType: AnyType, argTypes?: AnyType[]);
629
647
  /** The callback function pointer, passable to native functions. */
630
648
  readonly pointer: bigint;
631
- /** Same as {@link Callback.pointer}. */
649
+ /** Return the function pointer, throwing if the callback has been released. */
632
650
  getPointer(): bigint;
633
- /** Same as `pointer`: lets the callback be passed directly as an argument. */
634
- readonly _as_parameter_: bigint;
635
651
  /** Release the callback and free native resources. Must be called when done. */
636
652
  release(): void;
637
653
  /**
@@ -731,7 +747,11 @@ export type FieldSpec = AnyType | StructDef | ArrayTypeDef | BitFieldDef | Anony
731
747
  */
732
748
  export type JsFromCType<T> =
733
749
  T extends SimpleCDataConstructor<infer Tag>
734
- ? JsFromTag<Tag>
750
+ ? T extends { prototype: infer Instance }
751
+ ? IsAny<Instance> extends true
752
+ ? JsFromTag<Tag>
753
+ : Instance
754
+ : JsFromTag<Tag>
735
755
  : T extends BitFieldDef
736
756
  ? number
737
757
  : T extends PointerTypeDef<infer B>
@@ -789,10 +809,10 @@ type FieldValue<F extends Record<string, FieldSpec>, K extends keyof F> = string
789
809
  type FieldArg<F extends Record<string, FieldSpec>, K extends keyof F> = string extends keyof F ? any : JsArgFromCType<F[K]>;
790
810
 
791
811
  /**
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`.
812
+ * Numeric elements and scalar subclass instances are typed; other element
813
+ * representations retain the existing permissive array API.
794
814
  */
795
- type ArrayElement<E> = IsAny<E> extends true ? any : JsFromCType<E> extends number ? number : any;
815
+ type ArrayElement<E> = IsAny<E> extends true ? any : JsFromCType<E> extends SimpleCDataInstance<unknown> ? JsFromCType<E> : JsFromCType<E> extends number ? number : any;
796
816
 
797
817
  /** Element accepted when writing an array of `E`. */
798
818
  type ArrayElementArg<E> = IsAny<E> extends true ? any : E extends StructureClass ? Buffer | Record<string, any> : JsArgFromCType<E>;
@@ -801,7 +821,18 @@ type ArrayElementArg<E> = IsAny<E> extends true ? any : E extends StructureClass
801
821
  type PointerValue<T> = IsAny<T> extends true ? any : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
802
822
 
803
823
  /** `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>;
824
+ type PointerContents<T> =
825
+ IsAny<T> extends true
826
+ ? any
827
+ : T extends SimpleCDataConstructor<infer Tag>
828
+ ? T extends { prototype: infer Instance }
829
+ ? IsAny<Instance> extends true
830
+ ? SimpleCDataInstance<JsFromTag<Tag>>
831
+ : Instance
832
+ : SimpleCDataInstance<JsFromTag<Tag>>
833
+ : T extends StructureClass
834
+ ? InstanceType<T>
835
+ : JsFromCType<T>;
805
836
 
806
837
  /** `string` for `c_char`/`c_wchar` arrays (read as text, as Python), otherwise `Else`. */
807
838
  type CharArrayValue<E, Else> = IsAny<E> extends true ? Else : [E] extends [SimpleCDataConstructor<"char">] ? string : [E] extends [SimpleCDataConstructor<"wchar">] ? string : Else;
@@ -812,7 +843,7 @@ type CharArrayValue<E, Else> = IsAny<E> extends true ? Else : [E] extends [Simpl
812
843
  * `c_char` arrays also expose `.value`/`.raw` and `c_wchar` arrays `.value`.
813
844
  * @category Structures
814
845
  */
815
- export type ArrayInstance<E = any> = Omit<Buffer, ElementMethod | "length" | "toJSON"> &
846
+ export type ArrayInstance<E = any> = Omit<Buffer, ElementMethod | "length" | "toJSON" | number> &
816
847
  (IsAny<E> extends true
817
848
  ? ArrayProxy<any>
818
849
  : [E] extends [SimpleCDataConstructor<"char">]
@@ -857,7 +888,8 @@ type ArgsFromCTypes<TArgs extends readonly any[]> = {
857
888
  };
858
889
 
859
890
  /** 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>;
891
+ type JsArgFromFFIType<T> =
892
+ { 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
893
 
862
894
  /** Function arguments for `argtypes` `TArgs` (`any[]` when not a literal tuple). */
863
895
  type FFIArgs<TArgs extends readonly any[]> = FFIType[] extends TArgs ? any[] : { [K in keyof TArgs]: JsArgFromFFIType<TArgs[K]> };
@@ -868,7 +900,7 @@ type FFIArgs<TArgs extends readonly any[]> = FFIType[] extends TArgs ? any[] : {
868
900
  * restype a callable function (`null` for NULL) and a Structure/Union class an
869
901
  * instance of that class.
870
902
  */
871
- type FFIReturn<T> = FFIType extends T ? any : T extends null ? undefined : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
903
+ 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
904
 
873
905
  /**
874
906
  * A union type definition created by the {@link union} function.
@@ -1022,7 +1054,7 @@ export interface StructOptions {
1022
1054
  /** If `true`, disables padding between fields (as `pack: 1`). */
1023
1055
  packed?: boolean;
1024
1056
  /** Maximum field alignment in bytes, as Python's `_pack_`. */
1025
- pack?: number;
1057
+ pack?: number | boolean | bigint | string | null;
1026
1058
  /** Bit field layout, as Python's `_layout_` (`"ms"` with `pack`, otherwise the platform's). */
1027
1059
  layout?: "gcc-sysv" | "ms";
1028
1060
  /** Minimum alignment in bytes, as Python's `_align_`. */
@@ -1238,23 +1270,32 @@ export interface PointerTypeDef<T = any> {
1238
1270
 
1239
1271
  /**
1240
1272
  * Low-level native struct type. Prefer {@link Structure} for most use cases.
1273
+ * Mutable only until captured by a field, array, prepared function/callback
1274
+ * signature or native value. Finalization includes nested descriptors.
1275
+ * Create a new descriptor rather than modifying a finalized layout.
1241
1276
  * @category Structures
1242
1277
  */
1243
1278
  export class StructType {
1244
- constructor(isUnion?: boolean);
1245
- addField(name: string, type: AnyType | StructType | ArrayType): this;
1279
+ constructor(options?: { union?: boolean; alignment?: number; memoryClass?: boolean });
1280
+ /** Append a field while the builder is open; throws after finalization. */
1281
+ addField(name: string, type: number | StructType | ArrayType | { readonly _native: ArrayType }, options?: { anonymous?: boolean }): this;
1282
+ /** Query without finalizing an unused builder. */
1246
1283
  getSize(): number;
1284
+ /** Query without finalizing an unused builder. */
1247
1285
  getAlignment(): number;
1248
- create(values?: Record<string, any>): Buffer;
1286
+ /** Materialize a value and finalize its layout. */
1287
+ create(values?: Record<string, unknown>): Record<string, unknown> & { readonly _buffer: Buffer };
1249
1288
  read(buffer: Buffer): Record<string, any>;
1289
+ toObject(source: Buffer | { readonly _buffer: Buffer }): Record<string, unknown>;
1250
1290
  }
1251
1291
 
1252
1292
  /**
1253
1293
  * Low-level native array type. Prefer {@link array} for most use cases.
1294
+ * Captures and finalizes an aggregate element's layout, including at length zero.
1254
1295
  * @category Structures
1255
1296
  */
1256
1297
  export class ArrayType {
1257
- constructor(elementType: AnyType, count: number);
1298
+ constructor(elementType: number | StructType, count: number);
1258
1299
  getSize(): number;
1259
1300
  getLength(): number;
1260
1301
  getAlignment(): number;
@@ -1313,7 +1354,7 @@ export class Structure<F extends Record<string, FieldSpec> = Record<string, any>
1313
1354
  * Maximum field alignment in bytes, as Python's `_pack_` (`1` = no padding).
1314
1355
  * `true` is accepted as `1`.
1315
1356
  */
1316
- static _pack_?: number | boolean;
1357
+ static _pack_?: number | boolean | bigint | string | null;
1317
1358
 
1318
1359
  /**
1319
1360
  * Bit field layout, as Python's `_layout_`: `"gcc-sysv"` (default except on
@@ -1525,7 +1566,11 @@ export function load(path: string | null): Library;
1525
1566
  *
1526
1567
  * @category Callbacks
1527
1568
  */
1528
- export function callback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): CallbackWrapper;
1569
+ type CallbackRestype = SimpleCDataConstructor | PointerTypeDef | FuncPtrFactory | number | null;
1570
+ type CallbackArgs<T extends readonly FFIType[]> = { -readonly [K in keyof T]: JsFromCType<T[K]> };
1571
+ type CallbackResult<T> = T extends null | SimpleCDataConstructor<"void"> ? void : T extends StructureClass | StructDef | ArrayTypeDef ? never : JsArgFromCType<T> | (T extends SimpleCDataConstructor ? InstanceType<T> : never);
1572
+
1573
+ export function callback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>, returnType: TRet, argTypes?: TArgs): CallbackWrapper;
1529
1574
 
1530
1575
  /**
1531
1576
  * Create a thread-safe callback that can be invoked from any thread.
@@ -1540,7 +1585,7 @@ export function callback(fn: Function, returnType: AnyType | null, argTypes?: An
1540
1585
  *
1541
1586
  * @category Callbacks
1542
1587
  */
1543
- export function threadSafeCallback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): ThreadSafeCallbackWrapper;
1588
+ export function threadSafeCallback<TRet extends CallbackRestype, const TArgs extends readonly FFIType[] = readonly []>(fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>, returnType: TRet, argTypes?: TArgs): ThreadSafeCallbackWrapper;
1544
1589
 
1545
1590
  /**
1546
1591
  * Create a function pointer type with cdecl calling convention.
@@ -1577,8 +1622,8 @@ export function threadSafeCallback(fn: Function, returnType: AnyType | null, arg
1577
1622
  * @category Function Pointers
1578
1623
  */
1579
1624
  export interface ParamFlag {
1580
- /** `"in"` for input params (default), `"out"` for output params (POINTER(T) argtype). */
1581
- dir: "in" | "out";
1625
+ /** OUT allocates a pointee; INOUT uses and returns the supplied instance. */
1626
+ dir: "in" | "out" | "inout";
1582
1627
  /** Parameter name, used for the named-call form `fn({ name: value, ... })`. */
1583
1628
  name: string;
1584
1629
  /** Optional default value; applied when the caller omits this `in` param. */
@@ -1590,47 +1635,54 @@ export interface ParamFlag {
1590
1635
  *
1591
1636
  * @category Function Pointers
1592
1637
  */
1593
- export interface FuncPtrFactory {
1638
+ export interface FuncPtrFactory<TRet extends FFIType | null = FFIType | null, TArgs extends readonly FFIType[] = readonly FFIType[]> {
1594
1639
  /** Call with a raw address to produce a caller. */
1595
- (address: bigint | number): (...args: any[]) => any;
1640
+ (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
1641
+ new (address: bigint | number): TypedFFIFunction<TArgs, TRet>;
1596
1642
  /**
1597
1643
  * Call with a JS function to produce a C-callable callback closure, usable
1598
1644
  * as argument or struct field of this type. Keep it referenced while C may
1599
1645
  * call it; `release()` frees it.
1600
1646
  */
1601
- (fn: (...args: any[]) => any): { readonly pointer: bigint; readonly _as_parameter_: bigint; release(): void };
1647
+ (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallbackWrapper;
1648
+ new (fn: (...args: CallbackArgs<TArgs>) => CallbackResult<TRet>): CallbackWrapper;
1602
1649
  /**
1603
1650
  * Bind an exported function of a library, optionally with paramflags.
1604
1651
  * Python: `prototype((name, dll))` / `prototype((name, dll), paramflags)`.
1605
1652
  */
1606
- (spec: readonly [name: string, library: CDLL], paramflags?: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1653
+ (spec: readonly [name: string, library: CDLL]): TypedFFIFunction<TArgs, TRet>;
1654
+ (spec: readonly [name: string, library: CDLL], paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): FFIFunction;
1607
1655
 
1656
+ /** Shared metadata; assigning it does not recompile the captured signature. */
1608
1657
  restype: FFIType | null;
1658
+ /** Shared metadata; mutating it does not recompile the captured signature. */
1609
1659
  argtypes: FFIType[];
1610
1660
  readonly _isFuncPtr: true;
1611
1661
 
1612
1662
  /**
1613
1663
  * Bind the factory to a library export with Python-style paramflags.
1614
- * Out params are allocated automatically and returned as part of the tuple.
1664
+ * Out params are allocated automatically and returned alone (one value or
1665
+ * an array). Returning the original `args` from errcheck keeps this behavior.
1666
+ * `callAsync()` uses the same output processing and per-call hook snapshot.
1615
1667
  *
1616
1668
  * Python ctypes parity: `prototype((name, lib), paramflags)`.
1617
1669
  *
1618
1670
  * @example
1619
1671
  * ```javascript
1620
- * const proto = WINFUNCTYPE(BOOL, HWND, POINTER(DWORD), POINTER(DWORD));
1672
+ * const proto = WINFUNCTYPE(DWORD, HWND, LPDWORD);
1621
1673
  * const fn = proto.bind(user32, "GetWindowThreadProcessId", [
1622
1674
  * { dir: "in", name: "hWnd" },
1623
1675
  * { dir: "out", name: "pid" },
1624
- * { dir: "out", name: "tid" },
1625
1676
  * ]);
1626
- * const [ok, pid, tid] = fn(hwnd); // positional
1627
- * const [ok2, pid2, tid2] = fn({ hWnd: hwnd }); // named
1677
+ * const pid = fn(hwnd); // positional; thread ID is discarded
1678
+ * const pid2 = fn({ hWnd: hwnd }); // named
1679
+ * const pid3 = await fn.callAsync(hwnd); // async, same output processing
1628
1680
  * ```
1629
1681
  */
1630
- bind(library: CDLL, symbolName: string, paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1682
+ bind(library: CDLL, symbolName: string, paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): FFIFunction;
1631
1683
  }
1632
1684
 
1633
- export function CFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1685
+ export function CFUNCTYPE<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(restype: TRet, ...argtypes: TArgs): FuncPtrFactory<TRet, TArgs>;
1634
1686
 
1635
1687
  /**
1636
1688
  * Create a function pointer type with stdcall calling convention (Windows).
@@ -1645,7 +1697,7 @@ export function CFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): Func
1645
1697
  *
1646
1698
  * @category Callbacks
1647
1699
  */
1648
- export function WINFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1700
+ export function WINFUNCTYPE<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(restype: TRet, ...argtypes: TArgs): FuncPtrFactory<TRet, TArgs>;
1649
1701
 
1650
1702
  /**
1651
1703
  * Create a C string buffer (null-terminated).
@@ -1717,14 +1769,14 @@ export function wstring_at(address: Buffer | bigint | number, size?: number): st
1717
1769
  *
1718
1770
  * @category Memory
1719
1771
  */
1720
- export function addressof(ptr: Buffer | bigint | number): bigint;
1772
+ export function addressof(ptr: ArrayBufferView | ArrayBuffer | { readonly _buffer: Buffer } | PointerInstance | bigint | number): bigint;
1721
1773
 
1722
1774
  /**
1723
1775
  * Memory argument of {@link memmove} / {@link memset}: a buffer (any typed
1724
1776
  * array, DataView or ArrayBuffer, as bytes), a ctypes instance, a pointer or an
1725
1777
  * address.
1726
1778
  */
1727
- export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffer: Buffer } | PointerInstance | bigint | number;
1779
+ export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffer: Buffer } | { readonly _as_parameter_: unknown } | PointerInstance | bigint | number | null;
1728
1780
 
1729
1781
  /**
1730
1782
  * Copy memory from source to destination.
@@ -1733,7 +1785,7 @@ export type MemoryTarget = ArrayBufferView | ArrayBufferLike | { readonly _buffe
1733
1785
  *
1734
1786
  * @category Memory
1735
1787
  */
1736
- export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): void;
1788
+ export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): bigint;
1737
1789
 
1738
1790
  /**
1739
1791
  * Fill memory with a byte value.
@@ -1742,7 +1794,7 @@ export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): vo
1742
1794
  *
1743
1795
  * @category Memory
1744
1796
  */
1745
- export function memset(dst: MemoryTarget, value: number, count: number): void;
1797
+ export function memset(dst: MemoryTarget, value: number, count: number): bigint;
1746
1798
 
1747
1799
  /**
1748
1800
  * Read a typed value from a buffer at a given offset.
@@ -1884,6 +1936,10 @@ export interface DefinedClass<F extends Record<string, FieldSpec>, I> {
1884
1936
  /**
1885
1937
  * Define a fixed-size array type.
1886
1938
  *
1939
+ * Weakly interned by element type and count: live types keep their identity,
1940
+ * including when retained by instances, signatures or containing types.
1941
+ * The cache does not keep unused types alive.
1942
+ *
1887
1943
  * Python equivalent: `c_int * 5`
1888
1944
  *
1889
1945
  * @param elementType - Type of each element
@@ -1930,15 +1986,22 @@ export function ARRAY<E extends ArrayElementType>(elementType: E, count: number)
1930
1986
  export function bitfield(baseType: SimpleCDataConstructor, bits: number): BitFieldDef;
1931
1987
 
1932
1988
  /**
1933
- * Pass an object by reference (returns its underlying buffer).
1989
+ * Pass an object by reference, retaining its owner and applying a signed byte offset.
1990
+ * In-range references are Buffer views; out-of-range offsets are address carriers.
1934
1991
  *
1935
1992
  * Python equivalent: `ctypes.byref`
1936
1993
  *
1937
1994
  * @param obj - A Buffer, SimpleCData instance, or any object with a `_buffer` property
1995
+ * @param offset - Signed byte offset; the caller is responsible for valid external memory
1938
1996
  *
1939
1997
  * @category Pointers
1940
1998
  */
1941
- export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }): Buffer;
1999
+ export interface ByRefAddress {
2000
+ readonly address: bigint;
2001
+ readonly _as_parameter_: bigint;
2002
+ }
2003
+ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, offset?: 0): Buffer;
2004
+ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }, offset: number): Buffer | ByRefAddress;
1942
2005
 
1943
2006
  /**
1944
2007
  * Interpret a pointer as a different type.
@@ -1968,8 +2031,8 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }):
1968
2031
  *
1969
2032
  * @category Pointers
1970
2033
  */
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;
2034
+ export function cast<T>(ptr: MemorySource | ArrayBuffer | ByRefAddress | null, targetType: PointerTypeDef<T>): PointerInstance<T>;
2035
+ export function cast(ptr: MemorySource | ArrayBuffer | ByRefAddress | null, targetType: AnyType | StructDef | StructureClass): any;
1973
2036
 
1974
2037
  /**
1975
2038
  * Create a pointer type for a given base type.
@@ -2146,13 +2209,13 @@ export interface SimpleCDataConstructor<Tag extends string = string> {
2146
2209
  _writer(buf: Buffer, offset: number, value: JsArgFromTag<Tag>): void;
2147
2210
 
2148
2211
  /** Create an instance that aliases an existing Buffer (zero-copy). */
2149
- from_buffer(buffer: Buffer, offset?: number): SimpleCDataInstance<JsFromTag<Tag>>;
2212
+ from_buffer<T extends SimpleCDataConstructor<Tag>>(this: T, buffer: ArrayBufferView | { readonly _buffer: Buffer }, offset?: number): InstanceType<T>;
2150
2213
  /** Create an instance whose buffer is a copy of the source bytes. */
2151
- from_buffer_copy(buffer: Buffer, offset?: number): SimpleCDataInstance<JsFromTag<Tag>>;
2214
+ from_buffer_copy<T extends SimpleCDataConstructor<Tag>>(this: T, buffer: ArrayBufferView | { readonly _buffer: Buffer }, offset?: number): InstanceType<T>;
2152
2215
  /** Create an instance viewing raw memory at the given address. */
2153
- from_address(address: bigint | number): SimpleCDataInstance<JsFromTag<Tag>>;
2216
+ from_address<T extends SimpleCDataConstructor<Tag>>(this: T, address: bigint | number): InstanceType<T>;
2154
2217
  /** Bind this type to an exported global variable in a shared library. */
2155
- in_dll(library: CDLL | Library, name: string): SimpleCDataInstance<JsFromTag<Tag>>;
2218
+ in_dll<T extends SimpleCDataConstructor<Tag>>(this: T, library: CDLL | Library, name: string): InstanceType<T>;
2156
2219
  }
2157
2220
 
2158
2221
  /**
@@ -2224,6 +2287,8 @@ export interface SimpleCDataInstance<T = any> {
2224
2287
  toString(): string;
2225
2288
  toJSON(): T;
2226
2289
  valueOf(): T;
2290
+ /** OUT conversion; defaults to the value for builtins and the instance for subclasses. */
2291
+ __ctypes_from_outparam__(): unknown;
2227
2292
  }
2228
2293
 
2229
2294
  // =============================================================================
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
@@ -28,6 +28,25 @@
28
28
  */
29
29
 
30
30
  import { mirrorAddress } from "./mirror.js";
31
+ import { resolveParameter } from "../structures/helpers/common.js";
32
+
33
+ // Fixed backing stores do not move; resizable/growable stores are never cached.
34
+ const memoryAddresses = new WeakMap();
35
+
36
+ function destinationAddress(memory, native) {
37
+ if (memory === null) return 0n;
38
+ if (typeof memory === "bigint") return memory;
39
+ const buffer = memory.buffer;
40
+ const cached = memoryAddresses.get(buffer);
41
+ if (cached !== undefined && cached.length === buffer.byteLength) {
42
+ return memory.byteOffset === 0 ? cached.address : cached.address + BigInt(memory.byteOffset);
43
+ }
44
+ const address = native.addressOf(memory);
45
+ if (buffer.byteLength !== 0 && !buffer.resizable && !buffer.growable) {
46
+ memoryAddresses.set(buffer, { address: address - BigInt(memory.byteOffset), length: buffer.byteLength });
47
+ }
48
+ return address;
49
+ }
31
50
 
32
51
  /**
33
52
  * Allocates a zero-initialized buffer of the specified size.
@@ -459,16 +478,21 @@ function stringSource(value, native) {
459
478
  * ```
460
479
  */
461
480
  export function memmove(dst, src, count, native) {
462
- const to = memoryOf(dst, native, "dst");
463
- const from = memoryOf(src, native, "src");
481
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("memmove: count must be a non-negative safe integer");
482
+ const to = memoryOf(dst, native, "dst", count === 0);
483
+ const from = memoryOf(src, native, "src", count === 0);
484
+ if (count === 0) return destinationAddress(to, native);
464
485
  // Come Buffer.copy, la copia si ferma alla fine dei Buffer coinvolti.
465
486
  let n = count;
466
487
  if (typeof to !== "bigint") n = Math.min(n, to.length);
467
488
  if (typeof from !== "bigint") n = Math.min(n, from.length);
468
- if (n <= 0) return;
489
+ if (n <= 0) return destinationAddress(to, native);
469
490
  // TypedArray.set gestisce anche la sovrapposizione (stesso ArrayBuffer).
470
- if (typeof to !== "bigint" && typeof from !== "bigint") to.set(n === from.length ? from : from.subarray(0, n));
471
- else native.memmove(to, from, n);
491
+ if (typeof to !== "bigint" && typeof from !== "bigint") {
492
+ to.set(n === from.length ? from : from.subarray(0, n));
493
+ return destinationAddress(to, native);
494
+ }
495
+ return native.memmove(to, from, n);
472
496
  }
473
497
 
474
498
  // Memoria di un argomento di memmove/memset, come Python: Buffer, ogni
@@ -477,6 +501,10 @@ export function memmove(dst, src, count, native) {
477
501
  // Gli indirizzi (anche quello originale di una copia, memory/mirror.js) sono
478
502
  // letti e scritti dal nativo, senza creare un Buffer esterno.
479
503
  function memoryOf(value, native, name, allowNull = false) {
504
+ value = resolveParameter(value);
505
+ if (ArrayBuffer.isView(value) && value._buffer === undefined) {
506
+ return mirrorAddress(value) ?? (value instanceof Uint8Array ? value : new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
507
+ }
480
508
  if (value !== null && typeof value === "object") {
481
509
  // c_void_p / c_char_p / c_wchar_p: the memory they point to, as in Python.
482
510
  const T = value.constructor;
@@ -495,7 +523,7 @@ function memoryOf(value, native, name, allowNull = false) {
495
523
  if (value._as_parameter_ !== undefined) return memoryOf(value._as_parameter_, native, name, allowNull);
496
524
  }
497
525
  if (typeof value === "bigint" || typeof value === "number") return addressOrNull(value, name, allowNull);
498
- if (allowNull && value === null) return null;
526
+ if (value === null) return addressOrNull(0n, name, allowNull);
499
527
  throw new TypeError(`${name} must be a Buffer, a ctypes instance, a pointer or an address`);
500
528
  }
501
529
 
@@ -528,11 +556,14 @@ function addressOrNull(value, name, allowNull = false) {
528
556
  * ```
529
557
  */
530
558
  export function memset(dst, value, count, native) {
531
- const to = memoryOf(dst, native, "dst");
559
+ if (!Number.isSafeInteger(count) || count < 0) throw new RangeError("memset: count must be a non-negative safe integer");
560
+ const to = memoryOf(dst, native, "dst", count === 0);
561
+ if (count === 0) return destinationAddress(to, native);
532
562
  if (typeof to !== "bigint") {
533
563
  // Come memmove, si ferma alla fine della memoria JS.
534
564
  to.fill(value, 0, Math.max(0, Math.min(count, to.length)));
565
+ return destinationAddress(to, native);
535
566
  } else if (count > 0) {
536
- native.memmove(to, Buffer.alloc(count, value), count);
567
+ return native.memmove(to, Buffer.alloc(count, value), count);
537
568
  }
538
569
  }