node-ctypes 1.14.0 → 2.1.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
@@ -47,7 +47,7 @@
47
47
  *
48
48
  * const x = new c_int32(42);
49
49
  * const p = pointer(x);
50
- * console.log(p.contents); // 42
50
+ * console.log(p.contents.value); // 42
51
51
  * ```
52
52
  *
53
53
  * @packageDocumentation
@@ -91,6 +91,8 @@ export interface CTypeValues {
91
91
  readonly STRUCT: number;
92
92
  readonly UNION: number;
93
93
  readonly ARRAY: number;
94
+ /** `char` as a 1-byte character (Python `c_char`). */
95
+ readonly CHAR: number;
94
96
  readonly COUNT: number;
95
97
  }
96
98
 
@@ -106,6 +108,22 @@ export const CType: CTypeValues;
106
108
  */
107
109
  export type AnyType = SimpleCDataConstructor | number | StructDef | UnionDef;
108
110
 
111
+ /**
112
+ * A {@link Structure} or {@link Union} subclass used as a type
113
+ * (e.g. `class Point extends Structure { ... }` passed as `Point`).
114
+ * @category Types
115
+ */
116
+ export type StructureClass = abstract new (...args: any[]) => Structure<any>;
117
+
118
+ /**
119
+ * Any type accepted in a function signature (`argtypes` / `restype`):
120
+ * {@link AnyType}, a Structure/Union class (struct by value), a
121
+ * {@link POINTER} type, an {@link array} type or a {@link CFUNCTYPE} prototype
122
+ * (function pointer).
123
+ * @category Types
124
+ */
125
+ export type FFIType = AnyType | StructureClass | PointerTypeDef | ArrayTypeDef | FuncPtrFactory;
126
+
109
127
  // =============================================================================
110
128
  // Library & Function
111
129
  // =============================================================================
@@ -116,7 +134,7 @@ export type AnyType = SimpleCDataConstructor | number | StructDef | UnionDef;
116
134
  * @example
117
135
  * ```javascript
118
136
  * import { Version } from 'node-ctypes';
119
- * console.log(Version.toString()); // "1.5.0"
137
+ * console.log(Version.toString()); // "2.0.0"
120
138
  * ```
121
139
  *
122
140
  * @category Library Loading
@@ -138,8 +156,14 @@ export class Version {
138
156
  export class Library {
139
157
  constructor(path: string | null);
140
158
  /** Typed overload: narrows args/return when argTypes is a literal tuple. */
141
- func<TRet extends AnyType, const TArgs extends readonly AnyType[]>(name: string, returnType: TRet, argTypes: TArgs, options?: FunctionOptions): TypedFFIFunction<TArgs, TRet>;
142
- func(name: string, returnType: AnyType, argTypes?: AnyType[], options?: FunctionOptions): FFIFunction;
159
+ func<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(name: string, returnType: TRet, argTypes: TArgs, options?: FunctionOptions): NativeFFIFunction<TArgs, TRet>;
160
+ func(name: string, returnType: FFIType | null, argTypes?: FFIType[], options?: FunctionOptions): NativeFFIFunction;
161
+
162
+ /**
163
+ * Create a native callback. Note the argument order (return type, argument
164
+ * types, function), which differs from {@link callback} and {@link CDLL.callback}.
165
+ */
166
+ callback(returnType: AnyType, argTypes: AnyType[], fn: Function): Callback;
143
167
 
144
168
  /**
145
169
  * Get the address of a symbol in the library.
@@ -182,7 +206,7 @@ export interface FunctionOptions {
182
206
  export type ErrcheckCallback = (result: any, func: CallableFunction, args: any[]) => any;
183
207
 
184
208
  /**
185
- * A callable FFI function returned by {@link Library.func} or {@link CDLL.func}.
209
+ * A callable FFI function returned by {@link CDLL.func}.
186
210
  * @category Library Loading
187
211
  */
188
212
  export interface FFIFunction {
@@ -199,14 +223,45 @@ export interface FFIFunction {
199
223
  readonly address: bigint;
200
224
 
201
225
  /**
202
- * Error checking callback, called after every invocation.
226
+ * Error checking callback, called after every invocation (`null` when not set).
203
227
  * @see {@link ErrcheckCallback}
204
228
  */
205
229
  errcheck: ErrcheckCallback | null;
206
230
  }
207
231
 
208
232
  /**
209
- * Strongly-typed FFI function returned by `CDLL.func`/`Library.func` when the
233
+ * Low-level native function handle returned by {@link Library.func}.
234
+ *
235
+ * Unlike the functions returned by {@link CDLL.func}, it is not directly
236
+ * callable: invoke it with {@link NativeFFIFunction.call | call()}.
237
+ *
238
+ * @category Library Loading
239
+ */
240
+ export interface NativeFFIFunction<TArgs extends readonly FFIType[] = FFIType[], TRet extends FFIType | null = FFIType> {
241
+ /** Call the native function synchronously. */
242
+ call(...args: FFIArgs<TArgs>): FFIReturn<TRet>;
243
+
244
+ /** Call the native function asynchronously on a worker thread. */
245
+ callAsync(...args: FFIArgs<TArgs>): Promise<FFIReturn<TRet>>;
246
+
247
+ /** Set (or clear with `null`) the error checking callback. */
248
+ setErrcheck(callback: ErrcheckCallback | null): void;
249
+
250
+ /** `GetLastError()` (Windows) or `errno` captured after the last call, with `use_last_error`. */
251
+ getCapturedLastError(): number;
252
+
253
+ /** `errno` captured after the last call, with `use_errno`. */
254
+ getCapturedErrno(): number;
255
+
256
+ /** The function name, or its hex address for raw function pointers. */
257
+ readonly name: string;
258
+
259
+ /** The function address as BigInt. */
260
+ readonly address: bigint;
261
+ }
262
+
263
+ /**
264
+ * Strongly-typed FFI function returned by `CDLL.func` when the
210
265
  * argument types and return type are given as a literal tuple and constant respectively.
211
266
  *
212
267
  * Args and return are narrowed from the supplied CType constructors.
@@ -214,9 +269,9 @@ export interface FFIFunction {
214
269
  *
215
270
  * @category Library Loading
216
271
  */
217
- export interface TypedFFIFunction<TArgs extends readonly AnyType[], TRet extends AnyType> {
218
- (...args: ArgsFromCTypes<TArgs>): JsFromCType<TRet>;
219
- callAsync(...args: ArgsFromCTypes<TArgs>): Promise<JsFromCType<TRet>>;
272
+ export interface TypedFFIFunction<TArgs extends readonly FFIType[], TRet extends FFIType | null> {
273
+ (...args: FFIArgs<TArgs>): FFIReturn<TRet>;
274
+ callAsync(...args: FFIArgs<TArgs>): Promise<FFIReturn<TRet>>;
220
275
  readonly funcName: string;
221
276
  readonly address: bigint;
222
277
  errcheck: ErrcheckCallback | null;
@@ -256,6 +311,14 @@ export interface TypedFFIFunction<TArgs extends readonly AnyType[], TRet extends
256
311
  * @category Library Loading
257
312
  */
258
313
  export interface LibraryOptions {
314
+ /**
315
+ * `dlopen` flags combined with `RTLD_LAZY` (e.g. {@link RTLD_GLOBAL}).
316
+ * Ignored on Windows. Default: {@link DEFAULT_MODE}.
317
+ *
318
+ * Python ctypes parity: the `mode` argument of `CDLL(name, mode)`.
319
+ */
320
+ mode?: number;
321
+
259
322
  /**
260
323
  * Maximum size of the internal function cache. Default: 1000.
261
324
  */
@@ -282,9 +345,10 @@ export interface LibraryOptions {
282
345
  export class CDLL {
283
346
  /**
284
347
  * @param path - Path to the shared library, or `null` to load the current process
285
- * @param options - Optional library settings (cache size, use_last_error, use_errno)
348
+ * @param options - `dlopen` mode (as Python's `CDLL(name, mode)`) or library
349
+ * settings (mode, cache size, use_last_error, use_errno)
286
350
  */
287
- constructor(path: string | null, options?: LibraryOptions);
351
+ constructor(path: string | null, options?: number | LibraryOptions);
288
352
 
289
353
  /**
290
354
  * Get a callable function from the library.
@@ -296,8 +360,8 @@ export class CDLL {
296
360
  * @returns A callable function
297
361
  */
298
362
  /** Typed overload: narrows args/return when argTypes is a literal tuple. */
299
- func<TRet extends AnyType, const TArgs extends readonly AnyType[]>(name: string, returnType: TRet, argTypes: TArgs, options?: FunctionOptions): TypedFFIFunction<TArgs, TRet>;
300
- func(name: string, returnType: AnyType, argTypes?: AnyType[], options?: FunctionOptions): CallableFunction & { callAsync(...args: any[]): Promise<any>; errcheck: ErrcheckCallback | null };
363
+ func<TRet extends FFIType | null, const TArgs extends readonly FFIType[]>(name: string, returnType: TRet, argTypes: TArgs, options?: FunctionOptions): TypedFFIFunction<TArgs, TRet>;
364
+ func(name: string, returnType: FFIType | null, argTypes?: FFIType[], options?: FunctionOptions): FFIFunction;
301
365
 
302
366
  /**
303
367
  * Get the address of a symbol.
@@ -309,6 +373,15 @@ export class CDLL {
309
373
  /** Close the library and clear the function cache. */
310
374
  close(): void;
311
375
 
376
+ /** Close the library at the end of a `using` block. */
377
+ [Symbol.dispose](): void;
378
+
379
+ /**
380
+ * Create a native callback bound to this library's context.
381
+ * Call `release()` when it is no longer needed.
382
+ */
383
+ callback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): Callback;
384
+
312
385
  /**
313
386
  * Read the snapshotted `GetLastError()` (Windows) or `errno` from the most
314
387
  * recent call on this library. Requires `use_last_error: true` at
@@ -362,12 +435,12 @@ export interface FunctionWrapper {
362
435
  callAsync(...args: any[]): Promise<any>;
363
436
 
364
437
  /** Argument types. Set before calling. */
365
- argtypes: AnyType[];
438
+ argtypes: FFIType[];
366
439
 
367
- /** Return type. Set before calling. */
368
- restype: AnyType;
440
+ /** Return type (`null` for `void`, as Python's `None`). Set before calling. */
441
+ restype: FFIType | null;
369
442
 
370
- /** Optional error checking callback. */
443
+ /** Optional error checking callback (`null` when not set). */
371
444
  errcheck: ErrcheckCallback | null;
372
445
  }
373
446
 
@@ -389,7 +462,7 @@ export interface FunctionWrapper {
389
462
  * @category Library Loading
390
463
  */
391
464
  export class WinDLL extends CDLL {
392
- constructor(path: string, options?: LibraryOptions);
465
+ constructor(path: string, options?: number | LibraryOptions);
393
466
  }
394
467
 
395
468
  /**
@@ -439,7 +512,35 @@ export const HRESULT: SimpleCDataConstructor<"int32"> & { _isHResult: true };
439
512
  *
440
513
  * @category Library Loading
441
514
  */
442
- export const cdll: { [libName: string]: CDLL };
515
+ export const cdll: LibraryNamespace<CDLL>;
516
+
517
+ /**
518
+ * Lazy library namespace: attribute access loads (and caches) the library,
519
+ * `LoadLibrary(name)` always creates a new instance.
520
+ *
521
+ * Python equivalent: `ctypes.LibraryLoader` instances (`cdll`, `windll`, ...)
522
+ *
523
+ * @category Library Loading
524
+ */
525
+ export type LibraryNamespace<T extends CDLL> = { [libName: string]: T } & {
526
+ /** Load a library (new instance each time). Python: `cdll.LoadLibrary(name)`. */
527
+ LoadLibrary(name: string | null, options?: number | LibraryOptions): T;
528
+ };
529
+
530
+ /**
531
+ * Create a lazy library namespace for a DLL class.
532
+ *
533
+ * Python equivalent: `ctypes.LibraryLoader(dlltype)`
534
+ *
535
+ * @example
536
+ * ```javascript
537
+ * const mydll = new LibraryLoader(CDLL);
538
+ * const libm = mydll.LoadLibrary(find_library("m"));
539
+ * ```
540
+ *
541
+ * @category Library Loading
542
+ */
543
+ export const LibraryLoader: new <T extends CDLL>(dlltype: new (path: string, ...args: any[]) => T) => LibraryNamespace<T>;
443
544
 
444
545
  /**
445
546
  * Lazy-loading namespace for WinDLL libraries (Windows only).
@@ -449,7 +550,7 @@ export const cdll: { [libName: string]: CDLL };
449
550
  *
450
551
  * @category Library Loading
451
552
  */
452
- export const windll: { [libName: string]: WinDLL } | undefined;
553
+ export const windll: LibraryNamespace<WinDLL> | undefined;
453
554
 
454
555
  /**
455
556
  * Lazy-loading namespace for OleDLL libraries (Windows only).
@@ -459,7 +560,7 @@ export const windll: { [libName: string]: WinDLL } | undefined;
459
560
  *
460
561
  * @category Library Loading
461
562
  */
462
- export const oledll: { [libName: string]: OleDLL } | undefined;
563
+ export const oledll: LibraryNamespace<OleDLL> | undefined;
463
564
 
464
565
  // =============================================================================
465
566
  // Callbacks
@@ -477,8 +578,29 @@ export interface CallbackWrapper {
477
578
  /** The callback function pointer, passable to native functions. */
478
579
  readonly pointer: bigint;
479
580
 
581
+ /** Same as `pointer`: lets the callback be passed directly as an argument. */
582
+ readonly _as_parameter_: bigint;
583
+
480
584
  /** Release the callback and free native resources. Must be called when done. */
481
585
  release(): void;
586
+
587
+ /** Release the callback at the end of a `using` block. */
588
+ [Symbol.dispose](): void;
589
+ }
590
+
591
+ /**
592
+ * Wrapper returned by {@link threadSafeCallback}.
593
+ * @category Callbacks
594
+ */
595
+ export interface ThreadSafeCallbackWrapper extends CallbackWrapper {
596
+ /** Keep the Node.js event loop alive until released (the default). */
597
+ ref(): this;
598
+
599
+ /**
600
+ * Do not keep the Node.js event loop alive: the process can exit while the
601
+ * callback exists. Calls from other threads are delivered while it runs.
602
+ */
603
+ unref(): this;
482
604
  }
483
605
 
484
606
  /**
@@ -487,8 +609,21 @@ export interface CallbackWrapper {
487
609
  */
488
610
  export class Callback {
489
611
  constructor(fn: Function, returnType: AnyType, argTypes?: AnyType[]);
612
+ /** The callback function pointer, passable to native functions. */
490
613
  readonly pointer: bigint;
614
+ /** Same as {@link Callback.pointer}. */
615
+ getPointer(): bigint;
616
+ /** Same as `pointer`: lets the callback be passed directly as an argument. */
617
+ readonly _as_parameter_: bigint;
618
+ /** Release the callback and free native resources. Must be called when done. */
491
619
  release(): void;
620
+ /**
621
+ * Handler called with the error message when the JS function throws.
622
+ * Without a handler the error is reported with `process.emitWarning`.
623
+ */
624
+ setErrorHandler(handler: (message: string) => void): void;
625
+ /** Message of the last exception thrown by the JS function, or `null`. */
626
+ getLastError(): string | null;
492
627
  }
493
628
 
494
629
  /**
@@ -498,7 +633,12 @@ export class Callback {
498
633
  *
499
634
  * @category Callbacks
500
635
  */
501
- export class ThreadSafeCallback extends Callback {}
636
+ export class ThreadSafeCallback extends Callback {
637
+ /** Keep the Node.js event loop alive until released (the default). */
638
+ ref(): this;
639
+ /** Do not keep the Node.js event loop alive. */
640
+ unref(): this;
641
+ }
502
642
 
503
643
  // =============================================================================
504
644
  // Structures
@@ -531,7 +671,7 @@ export interface FieldDef {
531
671
  *
532
672
  * @category Structures
533
673
  */
534
- export interface StructDef {
674
+ export interface StructDef<F extends Record<string, FieldSpec> = Record<string, any>> {
535
675
  /** Total size of the struct in bytes. */
536
676
  readonly size: number;
537
677
  /** Alignment requirement in bytes. */
@@ -544,19 +684,27 @@ export interface StructDef {
544
684
  readonly _isStructType: true;
545
685
 
546
686
  /** Allocate a buffer and optionally initialize field values. */
547
- create(values?: Record<string, any>): Buffer;
687
+ create(values?: FieldsInput<F>): Buffer;
548
688
  /** Read a field value from a buffer. */
549
- get(buf: Buffer, fieldName: string): any;
689
+ get<K extends keyof F & string>(buf: Buffer, fieldName: K): FieldValue<F, K>;
550
690
  /** Write a field value to a buffer. */
551
- set(buf: Buffer, fieldName: string, value: any): void;
691
+ set<K extends keyof F & string>(buf: Buffer, fieldName: K, value: FieldArg<F, K>): void;
552
692
  /** Convert all fields to a plain JavaScript object. */
553
- toObject(buf: Buffer): Record<string, any>;
693
+ toObject(buf: Buffer): FieldsObject<F>;
554
694
  /** Get a view of a nested struct's buffer region. */
555
695
  getNestedBuffer(buf: Buffer, fieldName: string): Buffer;
556
696
  }
557
697
 
698
+ /**
699
+ * One entry of `_fields_`: `[name, type]` or `[name, type, bits]` for bit fields.
700
+ * The loose element form lets `static _fields_ = [["x", c_int]]` compile
701
+ * without `as const`, as written in Python.
702
+ * @category Structures
703
+ */
704
+ export type FieldEntry = readonly [string, FieldSpec] | readonly [string, FieldSpec, number] | ReadonlyArray<string | number | FieldSpec>;
705
+
558
706
  /** @category Structures */
559
- export type FieldSpec = AnyType | StructDef | ArrayTypeDef | BitFieldDef | AnonymousField | PointerTypeDef;
707
+ export type FieldSpec = AnyType | StructDef | ArrayTypeDef | BitFieldDef | AnonymousField | PointerTypeDef | StructureClass | FuncPtrFactory;
560
708
 
561
709
  /**
562
710
  * Map a field/arg type (CType constructor, struct, array, bitfield, pointer) to its
@@ -565,7 +713,21 @@ export type FieldSpec = AnyType | StructDef | ArrayTypeDef | BitFieldDef | Anony
565
713
  * @category Types
566
714
  */
567
715
  export type JsFromCType<T> =
568
- T extends SimpleCDataConstructor<infer Tag> ? JsFromTag<Tag> : T extends BitFieldDef ? number : T extends PointerTypeDef ? PointerInstance : T extends StructDef ? any : T extends UnionDef ? any : T extends ArrayTypeDef ? any : any;
716
+ T extends SimpleCDataConstructor<infer Tag>
717
+ ? JsFromTag<Tag>
718
+ : T extends BitFieldDef
719
+ ? number
720
+ : T extends PointerTypeDef<infer B>
721
+ ? PointerInstance<B> | null
722
+ : T extends FuncPtrFactory
723
+ ? ((...args: any[]) => any) | null
724
+ : T extends StructureClass
725
+ ? InstanceType<T>
726
+ : T extends StructDef<infer F>
727
+ ? FieldsObject<F>
728
+ : T extends ArrayTypeDef<infer E>
729
+ ? CharArrayValue<E, ArrayInstance<E>>
730
+ : any;
569
731
 
570
732
  /**
571
733
  * Map a field/arg type to accepted JavaScript **input** types (for writes / function args).
@@ -579,23 +741,101 @@ export type JsArgFromCType<T> =
579
741
  : T extends BitFieldDef
580
742
  ? number
581
743
  : T extends PointerTypeDef
582
- ? PointerInstance | Buffer | bigint | null
583
- : T extends StructDef
584
- ? Buffer | { _buffer: Buffer } | Record<string, any>
585
- : T extends UnionDef
744
+ ? PointerInstance | Buffer | bigint | null | { readonly _buffer: Buffer }
745
+ : T extends FuncPtrFactory
746
+ ? { readonly _as_parameter_: unknown } | bigint | null
747
+ : T extends StructDef
586
748
  ? Buffer | { _buffer: Buffer } | Record<string, any>
587
- : T extends ArrayTypeDef
588
- ? Buffer | ReadonlyArray<any>
589
- : any;
749
+ : T extends UnionDef
750
+ ? Buffer | { _buffer: Buffer } | Record<string, any>
751
+ : T extends ArrayTypeDef<infer E>
752
+ ? Buffer | ReadonlyArray<any> | CharArrayValue<E, never>
753
+ : any;
590
754
 
591
755
  type FieldsToInstance<F extends Record<string, FieldSpec>> = {
592
756
  [K in keyof F]: JsFromCType<F[K]>;
593
757
  };
594
758
 
759
+ /** `true` when `T` is `any`. */
760
+ type IsAny<T> = 0 extends 1 & T ? true : false;
761
+
762
+ /** Field values of a definition; `any` when the fields are not statically known. */
763
+ type FieldsObject<F extends Record<string, FieldSpec>> = string extends keyof F ? Record<string, any> : FieldsToInstance<F>;
764
+
765
+ /** Initial values accepted by `create()`. */
766
+ type FieldsInput<F extends Record<string, FieldSpec>> = string extends keyof F ? Record<string, any> : { [K in keyof F]?: JsArgFromCType<F[K]> };
767
+
768
+ /** Value read from field `K`. */
769
+ type FieldValue<F extends Record<string, FieldSpec>, K extends keyof F> = string extends keyof F ? any : JsFromCType<F[K]>;
770
+
771
+ /** Value accepted when writing field `K`. */
772
+ type FieldArg<F extends Record<string, FieldSpec>, K extends keyof F> = string extends keyof F ? any : JsArgFromCType<F[K]>;
773
+
774
+ /**
775
+ * Element read from an array of `E`. Narrowed only to `number`: arrays are
776
+ * also Buffers, whose numeric index is `number`, so other element types stay `any`.
777
+ */
778
+ type ArrayElement<E> = IsAny<E> extends true ? any : JsFromCType<E> extends number ? number : any;
779
+
780
+ /** Element accepted when writing an array of `E`. */
781
+ type ArrayElementArg<E> = IsAny<E> extends true ? any : E extends StructureClass ? Buffer | Record<string, any> : JsArgFromCType<E>;
782
+
783
+ /** Value read through a pointer to `T` (`p[i]`): the value for simple types, a live instance for structures. */
784
+ type PointerValue<T> = IsAny<T> extends true ? any : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
785
+
786
+ /** `p.contents`: a live instance on the pointed memory (Python parity). */
787
+ type PointerContents<T> = IsAny<T> extends true ? any : T extends SimpleCDataConstructor<infer Tag> ? SimpleCDataInstance<JsFromTag<Tag>> : T extends StructureClass ? InstanceType<T> : JsFromCType<T>;
788
+
789
+ /** `string` for `c_char`/`c_wchar` arrays (read as text, as Python), otherwise `Else`. */
790
+ type CharArrayValue<E, Else> = IsAny<E> extends true ? Else : [E] extends [SimpleCDataConstructor<"char">] ? string : [E] extends [SimpleCDataConstructor<"wchar">] ? string : Else;
791
+
792
+ /**
793
+ * Array instance: a Buffer with index access; `c_char` arrays also expose
794
+ * `.value`/`.raw` and `c_wchar` arrays `.value`, as in Python.
795
+ * @category Structures
796
+ */
797
+ export type ArrayInstance<E = any> = Buffer & ArrayProxy<ArrayElement<E>> & (IsAny<E> extends true ? {} : [E] extends [SimpleCDataConstructor<"char">] ? CharBufferValue : [E] extends [SimpleCDataConstructor<"wchar">] ? WideBufferValue : {});
798
+
799
+ /**
800
+ * Text accessors of `c_char` buffers (arrays, {@link create_string_buffer}).
801
+ * @category Memory
802
+ */
803
+ export interface CharBufferValue {
804
+ /** Bytes up to the first NUL, decoded as UTF-8. Python: `.value`. */
805
+ get value(): string;
806
+ set value(v: string | Uint8Array);
807
+ /** All bytes. Python: `.raw`. */
808
+ get raw(): Buffer;
809
+ set raw(v: string | Uint8Array);
810
+ }
811
+
812
+ /**
813
+ * Text accessor of `c_wchar` buffers (arrays, {@link create_unicode_buffer}).
814
+ * @category Memory
815
+ */
816
+ export interface WideBufferValue {
817
+ /** Characters up to the first NUL. Python: `.value`. */
818
+ get value(): string;
819
+ set value(v: string);
820
+ }
821
+
595
822
  type ArgsFromCTypes<TArgs extends readonly any[]> = {
596
823
  [K in keyof TArgs]: JsArgFromCType<TArgs[K]>;
597
824
  };
598
825
 
826
+ /** JS argument accepted for a function parameter of type `T`. */
827
+ type JsArgFromFFIType<T> = T extends StructureClass ? Buffer | { _buffer: Buffer } | Record<string, any> : JsArgFromCType<T>;
828
+
829
+ /** Function arguments for `argtypes` `TArgs` (`any[]` when not a literal tuple). */
830
+ type FFIArgs<TArgs extends readonly any[]> = FFIType[] extends TArgs ? any[] : { [K in keyof TArgs]: JsArgFromFFIType<TArgs[K]> };
831
+
832
+ /**
833
+ * JS value returned by a function with `restype` `T`. As in Python, a
834
+ * `POINTER(T)` restype returns a {@link PointerInstance} and a {@link CFUNCTYPE}
835
+ * restype a callable function (`null` for NULL).
836
+ */
837
+ type FFIReturn<T> = FFIType extends T ? any : T extends null ? undefined : T extends StructureClass ? Record<string, any> : JsFromCType<T>;
838
+
599
839
  /**
600
840
  * A union type definition created by the {@link union} function.
601
841
  *
@@ -604,7 +844,7 @@ type ArgsFromCTypes<TArgs extends readonly any[]> = {
604
844
  *
605
845
  * @category Structures
606
846
  */
607
- export interface UnionDef extends StructDef {
847
+ export interface UnionDef<F extends Record<string, FieldSpec> = Record<string, any>> extends StructDef<F> {
608
848
  readonly isUnion: true;
609
849
  }
610
850
 
@@ -637,18 +877,25 @@ export interface BitFieldDef {
637
877
  /**
638
878
  * An array type definition created by the {@link array} function.
639
879
  *
880
+ * Python equivalent: `c_int * 5`. Call it (with or without `new`) with the
881
+ * initial elements, as Python's `(c_int * 5)(1, 2, 3)`.
882
+ *
640
883
  * @example
641
884
  * ```javascript
642
885
  * const IntArray5 = array(c_int32, 5);
643
- * const arr = IntArray5.create([1, 2, 3, 4, 5]);
886
+ * const arr = IntArray5(1, 2, 3, 4, 5); // or IntArray5.create([1, 2, 3, 4, 5])
644
887
  * console.log(arr[0]); // 1
645
888
  * ```
646
889
  *
647
890
  * @category Structures
648
891
  */
649
- export interface ArrayTypeDef {
892
+ export interface ArrayTypeDef<E = any> {
893
+ /** Create an array initialized with the given elements (Python: `(c_int * 3)(1, 2, 3)`). */
894
+ (...values: ArrayElementArg<E>[]): ArrayInstance<E>;
895
+ /** Create an array initialized with the given elements. */
896
+ new (...values: ArrayElementArg<E>[]): ArrayInstance<E>;
650
897
  /** Element type. */
651
- readonly elementType: AnyType;
898
+ readonly elementType: AnyType | StructureClass | ArrayTypeDef | PointerTypeDef | FuncPtrFactory;
652
899
  /** Number of elements. */
653
900
  readonly length: number;
654
901
  /** @internal */
@@ -660,19 +907,22 @@ export interface ArrayTypeDef {
660
907
  getLength(): number;
661
908
  /** Element alignment. */
662
909
  getAlignment(): number;
663
- /** Create a new array, optionally initialized with values. Returns a Proxy with index access. */
664
- create(values?: any[]): Buffer & ArrayProxy;
910
+ /**
911
+ * Create a new array, optionally initialized with values (a string writes
912
+ * its char codes). Returns a Proxy with index access.
913
+ */
914
+ create(values?: ReadonlyArray<ArrayElementArg<E>> | string): ArrayInstance<E>;
665
915
  /** Wrap an existing buffer as an array with index access. */
666
- wrap(buffer: Buffer): Buffer & ArrayProxy;
916
+ wrap(buffer: Buffer): ArrayInstance<E>;
667
917
  }
668
918
 
669
919
  /**
670
920
  * Proxy interface for array index access and iteration.
671
921
  * @category Structures
672
922
  */
673
- export interface ArrayProxy {
674
- [index: number]: any;
675
- [Symbol.iterator](): Iterator<any>;
923
+ export interface ArrayProxy<T = any> {
924
+ [index: number]: T;
925
+ [Symbol.iterator](): Iterator<T>;
676
926
  }
677
927
 
678
928
  /**
@@ -707,7 +957,7 @@ export interface AnonymousField {
707
957
  * ```javascript
708
958
  * const IntPtr = POINTER(c_int32);
709
959
  * const p = IntPtr.fromBuffer(buf);
710
- * console.log(p.contents); // dereferenced value (like *p in C)
960
+ * console.log(p.contents.value); // dereferenced value (like *p in C)
711
961
  * console.log(p[0]); // same as p.contents
712
962
  * console.log(p[5]); // pointer arithmetic (like p[5] in C)
713
963
  * ```
@@ -723,9 +973,9 @@ export interface AnonymousField {
723
973
  *
724
974
  * @category Pointers
725
975
  */
726
- export interface PointerInstance {
976
+ export interface PointerInstance<T = any> {
727
977
  /** The pointer type definition this instance was created from. */
728
- readonly _pointerType: PointerTypeDef;
978
+ readonly _pointerType: PointerTypeDef<T>;
729
979
  /** The base type this pointer points to. */
730
980
  readonly _baseType: AnyType | StructDef;
731
981
  /** Size of the pointed-to type in bytes. */
@@ -735,24 +985,27 @@ export interface PointerInstance {
735
985
  readonly address: bigint;
736
986
 
737
987
  /**
738
- * Dereference the pointer — read/write the value at the pointed location.
739
- *
740
- * Python equivalent: `p.contents`
988
+ * The pointed object, as Python's `p.contents`: a live instance on the
989
+ * pointed memory (`p.contents.value` for simple types, `p.contents.x` for
990
+ * structures). Assigning an instance re-points the pointer to it; assigning
991
+ * a plain value writes it.
741
992
  *
742
993
  * @example
743
994
  * ```javascript
744
995
  * const p = POINTER(c_int32).fromBuffer(buf);
745
- * console.log(p.contents); // read value
746
- * p.contents = 42; // write value
996
+ * console.log(p.contents.value); // read value
997
+ * p.contents = 42; // write value
998
+ * p.contents = new c_int32(7); // re-point
747
999
  * ```
748
1000
  */
749
- contents: any;
1001
+ get contents(): PointerContents<T>;
1002
+ set contents(value: PointerContents<T> | JsArgFromCType<T>);
750
1003
 
751
1004
  /** The underlying buffer (if created from a buffer), or null. */
752
1005
  readonly _buffer: Buffer | null;
753
1006
 
754
- /** Alias for contents getter. */
755
- deref(): any;
1007
+ /** Alias for the contents getter. */
1008
+ deref(): PointerContents<T>;
756
1009
 
757
1010
  /**
758
1011
  * Set pointer to a new target (buffer or address).
@@ -782,19 +1035,19 @@ export interface PointerInstance {
782
1035
  * arr[2] = 99; // write to third element
783
1036
  * ```
784
1037
  */
785
- [index: number]: any;
1038
+ [index: number]: PointerValue<T>;
786
1039
 
787
1040
  /**
788
1041
  * Return a new pointer offset by `n` elements (not bytes), matching C's
789
1042
  * `ptr + n`. The pointer keeps the same element type.
790
1043
  */
791
- add(n: number): PointerInstance;
1044
+ add(n: number): PointerInstance<T>;
792
1045
 
793
1046
  /**
794
1047
  * Read `end - start` consecutive elements into a JS array, analogous to
795
1048
  * Python's `p[start:end]` on a POINTER(T).
796
1049
  */
797
- slice(start: number, end: number): any[];
1050
+ slice(start: number, end: number): PointerValue<T>[];
798
1051
  }
799
1052
 
800
1053
  /**
@@ -806,7 +1059,7 @@ export interface PointerInstance {
806
1059
  *
807
1060
  * // From existing buffer
808
1061
  * const p = IntPtr.fromBuffer(buf);
809
- * console.log(p.contents); // 42
1062
+ * console.log(p.contents.value); // 42
810
1063
  * console.log(p[0]); // 42
811
1064
  *
812
1065
  * // From raw address (e.g., from a struct's c_void_p field)
@@ -816,9 +1069,9 @@ export interface PointerInstance {
816
1069
  *
817
1070
  * @category Pointers
818
1071
  */
819
- export interface PointerTypeDef {
1072
+ export interface PointerTypeDef<T = any> {
820
1073
  /** The type this pointer points to. */
821
- readonly _pointerTo: AnyType | StructDef;
1074
+ readonly _pointerTo: AnyType | StructDef | StructureClass | PointerTypeDef;
822
1075
  /** Size of the pointed-to type. */
823
1076
  readonly _baseSize: number;
824
1077
  /** Pointer size (always 8 on 64-bit). */
@@ -833,7 +1086,7 @@ export interface PointerTypeDef {
833
1086
  * console.log(p.isNull); // true
834
1087
  * ```
835
1088
  */
836
- create(value?: Buffer | bigint | number): PointerInstance;
1089
+ create(value?: Buffer | bigint | number): PointerInstance<T>;
837
1090
 
838
1091
  /**
839
1092
  * Create a pointer from an existing buffer (points to that buffer's memory).
@@ -845,10 +1098,10 @@ export interface PointerTypeDef {
845
1098
  * const buf = Buffer.alloc(4);
846
1099
  * buf.writeInt32LE(42, 0);
847
1100
  * const p = POINTER(c_int32).fromBuffer(buf);
848
- * console.log(p.contents); // 42
1101
+ * console.log(p.contents.value); // 42
849
1102
  * ```
850
1103
  */
851
- fromBuffer(targetBuf: Buffer): PointerInstance;
1104
+ fromBuffer(targetBuf: Buffer): PointerInstance<T>;
852
1105
 
853
1106
  /**
854
1107
  * Create a pointer from a raw memory address.
@@ -867,7 +1120,7 @@ export interface PointerTypeDef {
867
1120
  * }
868
1121
  * ```
869
1122
  */
870
- fromAddress(address: bigint | number): PointerInstance;
1123
+ fromAddress(address: bigint | number): PointerInstance<T>;
871
1124
 
872
1125
  /**
873
1126
  * @deprecated Use pointer instance `.contents` instead.
@@ -959,17 +1212,20 @@ export class Structure<F extends Record<string, FieldSpec> = Record<string, any>
959
1212
  * ];
960
1213
  * ```
961
1214
  */
962
- static _fields_?: Array<[string, FieldSpec]> | Record<string, FieldSpec>;
1215
+ static _fields_?: ReadonlyArray<FieldEntry> | Record<string, FieldSpec>;
963
1216
 
964
- /** If `true`, disables padding between fields. */
965
- static _pack_?: boolean;
1217
+ /**
1218
+ * Maximum field alignment in bytes, as Python's `_pack_` (`1` = no padding).
1219
+ * `true` is accepted as `1`.
1220
+ */
1221
+ static _pack_?: number | boolean;
966
1222
 
967
1223
  /**
968
1224
  * List of field names whose members are promoted to the parent struct.
969
1225
  *
970
1226
  * Python equivalent: `_anonymous_`
971
1227
  */
972
- static _anonymous_?: string[];
1228
+ static _anonymous_?: ReadonlyArray<string>;
973
1229
 
974
1230
  /** Create instance with optional initial values. */
975
1231
  static create<ThisT extends Structure<F>>(this: new (...args: any[]) => ThisT, values?: Partial<FieldsToInstance<F>> | Buffer): ThisT;
@@ -1153,12 +1409,14 @@ export function load(path: string | null): Library;
1153
1409
  *
1154
1410
  * @category Callbacks
1155
1411
  */
1156
- export function callback(fn: Function, returnType: AnyType, argTypes?: AnyType[]): CallbackWrapper;
1412
+ export function callback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): CallbackWrapper;
1157
1413
 
1158
1414
  /**
1159
1415
  * Create a thread-safe callback that can be invoked from any thread.
1160
1416
  *
1161
1417
  * **Important:** Call `.release()` when the callback is no longer needed.
1418
+ * Like a timer, it keeps the Node.js event loop alive until released, unless
1419
+ * `.unref()` is called.
1162
1420
  *
1163
1421
  * @param fn - JavaScript function to wrap
1164
1422
  * @param returnType - Return type of the callback
@@ -1166,7 +1424,7 @@ export function callback(fn: Function, returnType: AnyType, argTypes?: AnyType[]
1166
1424
  *
1167
1425
  * @category Callbacks
1168
1426
  */
1169
- export function threadSafeCallback(fn: Function, returnType: AnyType, argTypes?: AnyType[]): CallbackWrapper;
1427
+ export function threadSafeCallback(fn: Function, returnType: AnyType | null, argTypes?: AnyType[]): ThreadSafeCallbackWrapper;
1170
1428
 
1171
1429
  /**
1172
1430
  * Create a function pointer type with cdecl calling convention.
@@ -1218,12 +1476,21 @@ export interface ParamFlag {
1218
1476
  */
1219
1477
  export interface FuncPtrFactory {
1220
1478
  /** Call with a raw address to produce a caller. */
1221
- (address: bigint): (...args: any[]) => any;
1222
- /** Call with a JS function to produce a C-callable callback closure. */
1223
- (fn: (...args: any[]) => any): { pointer: bigint; release(): void };
1479
+ (address: bigint | number): (...args: any[]) => any;
1480
+ /**
1481
+ * Call with a JS function to produce a C-callable callback closure, usable
1482
+ * as argument or struct field of this type. Keep it referenced while C may
1483
+ * call it; `release()` frees it.
1484
+ */
1485
+ (fn: (...args: any[]) => any): { readonly pointer: bigint; readonly _as_parameter_: bigint; release(): void };
1486
+ /**
1487
+ * Bind an exported function of a library, optionally with paramflags.
1488
+ * Python: `prototype((name, dll))` / `prototype((name, dll), paramflags)`.
1489
+ */
1490
+ (spec: readonly [name: string, library: CDLL], paramflags?: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1224
1491
 
1225
- restype: AnyType;
1226
- argtypes: AnyType[];
1492
+ restype: FFIType | null;
1493
+ argtypes: FFIType[];
1227
1494
  readonly _isFuncPtr: true;
1228
1495
 
1229
1496
  /**
@@ -1244,10 +1511,10 @@ export interface FuncPtrFactory {
1244
1511
  * const [ok2, pid2, tid2] = fn({ hWnd: hwnd }); // named
1245
1512
  * ```
1246
1513
  */
1247
- bind(library: CDLL, symbolName: string, paramflags: ParamFlag[]): (...args: any[]) => any;
1514
+ bind(library: CDLL, symbolName: string, paramflags: ReadonlyArray<ParamFlag | readonly [flag: number, name?: string, defaultValue?: any]>): (...args: any[]) => any;
1248
1515
  }
1249
1516
 
1250
- export function CFUNCTYPE(restype: AnyType, ...argtypes: AnyType[]): FuncPtrFactory;
1517
+ export function CFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1251
1518
 
1252
1519
  /**
1253
1520
  * Create a function pointer type with stdcall calling convention (Windows).
@@ -1262,7 +1529,7 @@ export function CFUNCTYPE(restype: AnyType, ...argtypes: AnyType[]): FuncPtrFact
1262
1529
  *
1263
1530
  * @category Callbacks
1264
1531
  */
1265
- export function WINFUNCTYPE(restype: AnyType, ...argtypes: AnyType[]): FuncPtrFactory;
1532
+ export function WINFUNCTYPE(restype: FFIType | null, ...argtypes: FFIType[]): FuncPtrFactory;
1266
1533
 
1267
1534
  /**
1268
1535
  * Create a C string buffer (null-terminated).
@@ -1282,7 +1549,13 @@ export function WINFUNCTYPE(restype: AnyType, ...argtypes: AnyType[]): FuncPtrFa
1282
1549
  *
1283
1550
  * @category Memory
1284
1551
  */
1285
- export function create_string_buffer(init: number | string | Buffer): Buffer;
1552
+ export function create_string_buffer(init: number | string | Uint8Array, size?: number): Buffer & CharBufferValue;
1553
+
1554
+ /**
1555
+ * Alias of {@link create_string_buffer}. Python equivalent: `ctypes.c_buffer`.
1556
+ * @category Memory
1557
+ */
1558
+ export function c_buffer(init: number | string | Uint8Array, size?: number): Buffer & CharBufferValue;
1286
1559
 
1287
1560
  /**
1288
1561
  * Create a wide string buffer (wchar_t, null-terminated).
@@ -1295,7 +1568,7 @@ export function create_string_buffer(init: number | string | Buffer): Buffer;
1295
1568
  *
1296
1569
  * @category Memory
1297
1570
  */
1298
- export function create_unicode_buffer(init: number | string): Buffer;
1571
+ export function create_unicode_buffer(init: number | string, size?: number): Buffer & WideBufferValue;
1299
1572
 
1300
1573
  /**
1301
1574
  * Read a C string from an address or buffer.
@@ -1337,7 +1610,10 @@ export function addressof(ptr: Buffer | bigint | number): bigint;
1337
1610
  *
1338
1611
  * @category Memory
1339
1612
  */
1340
- export function memmove(dst: Buffer, src: Buffer | bigint, count: number): void;
1613
+ /** Memory argument of {@link memmove} / {@link memset}: a buffer, a ctypes instance, a pointer or an address. */
1614
+ export type MemoryTarget = Uint8Array | { readonly _buffer: Buffer } | PointerInstance | bigint | number;
1615
+
1616
+ export function memmove(dst: MemoryTarget, src: MemoryTarget, count: number): void;
1341
1617
 
1342
1618
  /**
1343
1619
  * Fill memory with a byte value.
@@ -1346,7 +1622,7 @@ export function memmove(dst: Buffer, src: Buffer | bigint, count: number): void;
1346
1622
  *
1347
1623
  * @category Memory
1348
1624
  */
1349
- export function memset(dst: Buffer, value: number, count: number): void;
1625
+ export function memset(dst: MemoryTarget, value: number, count: number): void;
1350
1626
 
1351
1627
  /**
1352
1628
  * Read a typed value from a buffer at a given offset.
@@ -1364,8 +1640,8 @@ export function memset(dst: Buffer, value: number, count: number): void;
1364
1640
  *
1365
1641
  * @category Memory
1366
1642
  */
1367
- export function readValue<T extends AnyType>(ptr: Buffer | bigint | number, type: T, offset?: number): JsFromCType<T>;
1368
- export function readValue(ptr: Buffer | bigint | number, type: AnyType, offset?: number): any;
1643
+ export function readValue<T extends AnyType>(ptr: Buffer | bigint | number | PointerInstance, type: T, offset?: number): JsFromCType<T>;
1644
+ export function readValue(ptr: Buffer | bigint | number | PointerInstance, type: AnyType | StructureClass, offset?: number): any;
1369
1645
 
1370
1646
  /**
1371
1647
  * Write a typed value to a buffer at a given offset.
@@ -1377,8 +1653,8 @@ export function readValue(ptr: Buffer | bigint | number, type: AnyType, offset?:
1377
1653
  *
1378
1654
  * @category Memory
1379
1655
  */
1380
- export function writeValue<T extends AnyType>(ptr: Buffer | bigint | number, type: T, value: JsArgFromCType<T>, offset?: number): number | void;
1381
- export function writeValue(ptr: Buffer | bigint | number, type: AnyType, value: any, offset?: number): number | void;
1656
+ export function writeValue<T extends AnyType>(ptr: Buffer | bigint | number | PointerInstance, type: T, value: JsArgFromCType<T>, offset?: number): number | void;
1657
+ export function writeValue(ptr: Buffer | bigint | number | PointerInstance, type: AnyType | StructureClass, value: any, offset?: number): number | void;
1382
1658
 
1383
1659
  /**
1384
1660
  * Get the size of a type in bytes.
@@ -1394,7 +1670,7 @@ export function writeValue(ptr: Buffer | bigint | number, type: AnyType, value:
1394
1670
  *
1395
1671
  * @category Memory
1396
1672
  */
1397
- export function sizeof(type: AnyType | StructDef | ArrayTypeDef): number;
1673
+ export function sizeof(type: AnyType | StructDef | ArrayTypeDef | StructureClass | PointerTypeDef | FuncPtrFactory | SimpleCDataInstance | Structure<any> | Uint8Array): number;
1398
1674
 
1399
1675
  /**
1400
1676
  * Get the alignment requirement of a type in bytes.
@@ -1410,7 +1686,7 @@ export function sizeof(type: AnyType | StructDef | ArrayTypeDef): number;
1410
1686
  *
1411
1687
  * @category Memory
1412
1688
  */
1413
- export function alignment(type: AnyType | StructDef | ArrayTypeDef | typeof Structure | typeof Union): number;
1689
+ export function alignment(type: AnyType | StructDef | ArrayTypeDef | StructureClass | PointerTypeDef | FuncPtrFactory | SimpleCDataInstance | Structure<any>): number;
1414
1690
 
1415
1691
  /**
1416
1692
  * Create a Buffer view of native memory at a given address.
@@ -1441,7 +1717,7 @@ export function ptrToBuffer(address: bigint | number, size: number): Buffer;
1441
1717
  *
1442
1718
  * @category Structures
1443
1719
  */
1444
- export function struct(fields: Record<string, FieldSpec>, options?: StructOptions): StructDef;
1720
+ export function struct<F extends Record<string, FieldSpec>>(fields: F, options?: StructOptions): StructDef<F>;
1445
1721
 
1446
1722
  /**
1447
1723
  * Define a union using the functional API.
@@ -1452,7 +1728,7 @@ export function struct(fields: Record<string, FieldSpec>, options?: StructOption
1452
1728
  *
1453
1729
  * @category Structures
1454
1730
  */
1455
- export function union(fields: Record<string, FieldSpec>): UnionDef;
1731
+ export function union<F extends Record<string, FieldSpec>>(fields: F): UnionDef<F>;
1456
1732
 
1457
1733
  /**
1458
1734
  * Factory that returns a Structure subclass with typed fields.
@@ -1490,7 +1766,13 @@ export function defineUnion<F extends Record<string, FieldSpec>>(fields: F): new
1490
1766
  *
1491
1767
  * @category Structures
1492
1768
  */
1493
- export function array(elementType: AnyType | typeof Structure | typeof Union, count: number): ArrayTypeDef;
1769
+ export function array<E extends AnyType | StructureClass | ArrayTypeDef | PointerTypeDef | FuncPtrFactory>(elementType: E, count: number): ArrayTypeDef<E>;
1770
+
1771
+ /**
1772
+ * Alias of {@link array}. Python equivalent: `ctypes.ARRAY(type, length)`.
1773
+ * @category Structures
1774
+ */
1775
+ export function ARRAY<E extends AnyType | StructureClass | ArrayTypeDef | PointerTypeDef | FuncPtrFactory>(elementType: E, count: number): ArrayTypeDef<E>;
1494
1776
 
1495
1777
  /**
1496
1778
  * Define a bit field for use in struct `_fields_`.
@@ -1551,8 +1833,8 @@ export function byref(obj: Buffer | SimpleCDataInstance | { _buffer: Buffer }):
1551
1833
  *
1552
1834
  * @category Pointers
1553
1835
  */
1554
- export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: PointerTypeDef): PointerInstance;
1555
- export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: AnyType | StructDef): any;
1836
+ export function cast<T>(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: PointerTypeDef<T>): PointerInstance<T>;
1837
+ export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, targetType: AnyType | StructDef | StructureClass): any;
1556
1838
 
1557
1839
  /**
1558
1840
  * Create a pointer type for a given base type.
@@ -1569,7 +1851,7 @@ export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, target
1569
1851
  * buf.writeInt32LE(42, 0);
1570
1852
  *
1571
1853
  * const p = IntPtr.fromBuffer(buf);
1572
- * console.log(p.contents); // 42
1854
+ * console.log(p.contents.value); // 42
1573
1855
  * console.log(p[0]); // 42
1574
1856
  * ```
1575
1857
  *
@@ -1588,7 +1870,9 @@ export function cast(ptr: Buffer | bigint | number | SimpleCDataInstance, target
1588
1870
  *
1589
1871
  * @category Pointers
1590
1872
  */
1591
- export function POINTER(baseType: AnyType | StructDef): PointerTypeDef;
1873
+ export function POINTER<T extends AnyType | StructureClass | PointerTypeDef>(baseType: T): PointerTypeDef<T>;
1874
+ /** Lazy base type, for self-referential structs: `POINTER(() => Node)`. */
1875
+ export function POINTER<T extends AnyType | StructureClass>(baseType: () => T): PointerTypeDef<T>;
1592
1876
 
1593
1877
  /**
1594
1878
  * Create a pointer to an existing ctypes object.
@@ -1602,14 +1886,16 @@ export function POINTER(baseType: AnyType | StructDef): PointerTypeDef;
1602
1886
  * ```javascript
1603
1887
  * const x = new c_int32(42);
1604
1888
  * const p = pointer(x);
1605
- * console.log(p.contents); // 42
1889
+ * console.log(p.contents.value); // 42
1606
1890
  * p.contents = 100;
1607
1891
  * console.log(x.value); // 100
1608
1892
  * ```
1609
1893
  *
1610
1894
  * @category Pointers
1611
1895
  */
1612
- export function pointer(obj: SimpleCDataInstance | { _buffer: Buffer }): PointerInstance;
1896
+ export function pointer<T extends Structure<any>>(obj: T): PointerInstance<new (...args: any[]) => T>;
1897
+ export function pointer<V>(obj: SimpleCDataInstance<V>): PointerInstance;
1898
+ export function pointer(obj: Buffer | { _buffer: Buffer }): PointerInstance;
1613
1899
 
1614
1900
  /**
1615
1901
  * Get the C library errno value.
@@ -1643,7 +1929,35 @@ export function GetLastError(): number;
1643
1929
  *
1644
1930
  * @category Error Handling
1645
1931
  */
1646
- export function SetLastError(code: number): void;
1932
+ export function SetLastError(code: number): number;
1933
+
1934
+ /**
1935
+ * Python name of {@link GetLastError}: the error code captured by the last
1936
+ * call. Python equivalent: `ctypes.get_last_error()`
1937
+ *
1938
+ * @category Error Handling
1939
+ */
1940
+ export function get_last_error(): number;
1941
+
1942
+ /**
1943
+ * Python name of {@link SetLastError}; returns the previous value.
1944
+ * Python equivalent: `ctypes.set_last_error(value)`
1945
+ *
1946
+ * @category Error Handling
1947
+ */
1948
+ export function set_last_error(code: number): number;
1949
+
1950
+ /**
1951
+ * Raised when a function argument cannot be converted to its `argtypes` type,
1952
+ * with the message `"argument N: TypeError: ..."`. Subclass of `TypeError`.
1953
+ *
1954
+ * Python equivalent: `ctypes.ArgumentError`
1955
+ *
1956
+ * @category Error Handling
1957
+ */
1958
+ export class ArgumentError extends TypeError {
1959
+ constructor(message?: string);
1960
+ }
1647
1961
 
1648
1962
  /**
1649
1963
  * Format a Windows error code into a human-readable message (Windows only).
@@ -1712,19 +2026,21 @@ export interface SimpleCDataConstructor<Tag extends string = string> {
1712
2026
  */
1713
2027
  export type JsFromTag<Tag extends string> = Tag extends "void"
1714
2028
  ? void
1715
- : Tag extends "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "float" | "double" | "char" | "wchar"
1716
- ? number
1717
- : Tag extends "int64" | "uint64" | "size_t" | "ssize_t" | "long" | "ulong"
1718
- ? bigint
1719
- : Tag extends "bool"
1720
- ? boolean
1721
- : Tag extends "string"
1722
- ? string | null
1723
- : Tag extends "wstring"
2029
+ : Tag extends "char" | "wchar"
2030
+ ? string
2031
+ : Tag extends "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "float" | "double"
2032
+ ? number
2033
+ : Tag extends "int64" | "uint64" | "size_t" | "ssize_t" | "long" | "ulong"
2034
+ ? bigint
2035
+ : Tag extends "bool"
2036
+ ? boolean
2037
+ : Tag extends "string"
1724
2038
  ? string | null
1725
- : Tag extends "pointer"
1726
- ? bigint | Buffer | null
1727
- : any;
2039
+ : Tag extends "wstring"
2040
+ ? string | null
2041
+ : Tag extends "pointer"
2042
+ ? bigint | Buffer | null
2043
+ : any;
1728
2044
 
1729
2045
  /**
1730
2046
  * Maps a SimpleCData tag to accepted JavaScript **input** types (what writes/args accept).
@@ -1734,19 +2050,23 @@ export type JsFromTag<Tag extends string> = Tag extends "void"
1734
2050
  */
1735
2051
  export type JsArgFromTag<Tag extends string> = Tag extends "void"
1736
2052
  ? never
1737
- : Tag extends "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "float" | "double" | "char" | "wchar"
1738
- ? number
1739
- : Tag extends "int64" | "uint64" | "size_t" | "ssize_t" | "long" | "ulong"
1740
- ? bigint | number
1741
- : Tag extends "bool"
1742
- ? boolean | number
1743
- : Tag extends "string"
1744
- ? string | Buffer | null
1745
- : Tag extends "wstring"
1746
- ? string | Buffer | null
1747
- : Tag extends "pointer"
1748
- ? bigint | Buffer | number | null
1749
- : any;
2053
+ : Tag extends "char"
2054
+ ? string | number | Uint8Array
2055
+ : Tag extends "wchar"
2056
+ ? string | number
2057
+ : Tag extends "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" | "float" | "double"
2058
+ ? number
2059
+ : Tag extends "int64" | "uint64" | "size_t" | "ssize_t" | "long" | "ulong"
2060
+ ? bigint | number
2061
+ : Tag extends "bool"
2062
+ ? boolean | number
2063
+ : Tag extends "string"
2064
+ ? string | Buffer | null
2065
+ : Tag extends "wstring"
2066
+ ? string | Buffer | null
2067
+ : Tag extends "pointer"
2068
+ ? bigint | Buffer | number | null | { readonly _as_parameter_: unknown }
2069
+ : any;
1750
2070
 
1751
2071
  /**
1752
2072
  * Instance of a simple C data type.
@@ -1807,11 +2127,20 @@ export const c_uint64: SimpleCDataConstructor<"uint64">;
1807
2127
  export const c_float: SimpleCDataConstructor<"float">;
1808
2128
  /** 64-bit double. Python: `ctypes.c_double` @category Types */
1809
2129
  export const c_double: SimpleCDataConstructor<"double">;
1810
- /** 8-bit character. Python: `ctypes.c_char` @category Types */
2130
+ /**
2131
+ * 1-byte character. Python: `ctypes.c_char`. Values are 1-character strings
2132
+ * (Python `bytes` of length 1); writes also accept a byte number (0..255) or a
2133
+ * 1-byte Buffer.
2134
+ * @category Types
2135
+ */
1811
2136
  export const c_char: SimpleCDataConstructor<"char">;
1812
2137
  /** Pointer to null-terminated string. Python: `ctypes.c_char_p` @category Types */
1813
2138
  export const c_char_p: SimpleCDataConstructor<"string">;
1814
- /** Wide character. Python: `ctypes.c_wchar` @category Types */
2139
+ /**
2140
+ * Wide character (`wchar_t`). Python: `ctypes.c_wchar`. Values are 1-character
2141
+ * strings; writes also accept a code point number.
2142
+ * @category Types
2143
+ */
1815
2144
  export const c_wchar: SimpleCDataConstructor<"wchar">;
1816
2145
  /** Pointer to null-terminated wide string. Python: `ctypes.c_wchar_p` @category Types */
1817
2146
  export const c_wchar_p: SimpleCDataConstructor<"wstring">;
@@ -1840,6 +2169,213 @@ export const c_ushort: SimpleCDataConstructor<"uint16">;
1840
2169
  export const c_longlong: SimpleCDataConstructor<"int64">;
1841
2170
  /** Alias for `c_uint64`. Python: `ctypes.c_ulonglong` @category Types */
1842
2171
  export const c_ulonglong: SimpleCDataConstructor<"uint64">;
2172
+ /** Alias of {@link c_void_p}. Python: `ctypes.c_voidp` @category Types */
2173
+ export const c_voidp: SimpleCDataConstructor<"pointer">;
2174
+ /** `time_t` (64-bit). Python: `ctypes.c_time_t` @category Types */
2175
+ export const c_time_t: SimpleCDataConstructor<"int64">;
2176
+
2177
+ /**
2178
+ * A Structure class with known fields (used by {@link wintypes}).
2179
+ * @category Types
2180
+ */
2181
+ export type StructureOf<T> = (new (...args: any[]) => Structure<any> & T) & Omit<typeof Structure, "prototype">;
2182
+
2183
+ type W_BYTE = SimpleCDataConstructor<"uint8">;
2184
+ type W_WORD = SimpleCDataConstructor<"uint16">;
2185
+ type W_DWORD = SimpleCDataConstructor<"ulong">;
2186
+ type W_LONG = SimpleCDataConstructor<"long">;
2187
+ type W_SHORT = SimpleCDataConstructor<"int16">;
2188
+ type W_HANDLE = SimpleCDataConstructor<"pointer">;
2189
+ type W_RECT = StructureOf<{ left: bigint; top: bigint; right: bigint; bottom: bigint }>;
2190
+ type W_POINT = StructureOf<{ x: bigint; y: bigint }>;
2191
+ type W_SIZE = StructureOf<{ cx: bigint; cy: bigint }>;
2192
+ type W_SMALL_RECT = StructureOf<{ Left: number; Top: number; Right: number; Bottom: number }>;
2193
+ type W_FILETIME = StructureOf<{ dwLowDateTime: bigint; dwHighDateTime: bigint }>;
2194
+ type W_MSG = StructureOf<{ hWnd: bigint | null; message: number; wParam: bigint; lParam: bigint; time: bigint; pt: InstanceType<W_POINT> }>;
2195
+ type W_FIND_DATA = StructureOf<{
2196
+ dwFileAttributes: bigint;
2197
+ ftCreationTime: InstanceType<W_FILETIME>;
2198
+ ftLastAccessTime: InstanceType<W_FILETIME>;
2199
+ ftLastWriteTime: InstanceType<W_FILETIME>;
2200
+ nFileSizeHigh: bigint;
2201
+ nFileSizeLow: bigint;
2202
+ dwReserved0: bigint;
2203
+ dwReserved1: bigint;
2204
+ cFileName: string;
2205
+ cAlternateFileName: string;
2206
+ }>;
2207
+
2208
+ /**
2209
+ * Windows API types, as Python's `ctypes.wintypes`: the same names, aliases,
2210
+ * structures (`RECT`, `POINT`, `SIZE`, `MSG`, `FILETIME`, ...) and pointer
2211
+ * types (`LPDWORD = POINTER(DWORD)`, ...), plus common extras (`QWORD`,
2212
+ * `LRESULT`, `UINT_PTR`, `LSTATUS`, ...). Available on every platform.
2213
+ *
2214
+ * @example
2215
+ * ```javascript
2216
+ * import { wintypes } from "node-ctypes";
2217
+ * const { HWND, UINT, RECT, LPRECT } = wintypes;
2218
+ * ```
2219
+ *
2220
+ * @category Types
2221
+ */
2222
+ export const wintypes: {
2223
+ readonly BYTE: W_BYTE;
2224
+ readonly WORD: W_WORD;
2225
+ readonly DWORD: W_DWORD;
2226
+ readonly CHAR: SimpleCDataConstructor<"char">;
2227
+ readonly WCHAR: SimpleCDataConstructor<"wchar">;
2228
+ readonly UINT: SimpleCDataConstructor<"uint32">;
2229
+ readonly INT: SimpleCDataConstructor<"int32">;
2230
+ readonly DOUBLE: SimpleCDataConstructor<"double">;
2231
+ readonly FLOAT: SimpleCDataConstructor<"float">;
2232
+ readonly BOOLEAN: W_BYTE;
2233
+ readonly BOOL: W_LONG;
2234
+ readonly VARIANT_BOOL: SimpleCDataConstructor<"bool">;
2235
+ readonly ULONG: W_DWORD;
2236
+ readonly LONG: W_LONG;
2237
+ readonly USHORT: W_WORD;
2238
+ readonly SHORT: W_SHORT;
2239
+ readonly _LARGE_INTEGER: SimpleCDataConstructor<"int64">;
2240
+ readonly LARGE_INTEGER: SimpleCDataConstructor<"int64">;
2241
+ readonly _ULARGE_INTEGER: SimpleCDataConstructor<"uint64">;
2242
+ readonly ULARGE_INTEGER: SimpleCDataConstructor<"uint64">;
2243
+ readonly LPCOLESTR: SimpleCDataConstructor<"wstring">;
2244
+ readonly LPOLESTR: SimpleCDataConstructor<"wstring">;
2245
+ readonly OLESTR: SimpleCDataConstructor<"wstring">;
2246
+ readonly LPCWSTR: SimpleCDataConstructor<"wstring">;
2247
+ readonly LPWSTR: SimpleCDataConstructor<"wstring">;
2248
+ readonly LPCSTR: SimpleCDataConstructor<"string">;
2249
+ readonly LPSTR: SimpleCDataConstructor<"string">;
2250
+ readonly LPCVOID: W_HANDLE;
2251
+ readonly LPVOID: W_HANDLE;
2252
+ readonly WPARAM: SimpleCDataConstructor<"size_t">;
2253
+ readonly LPARAM: SimpleCDataConstructor<"ssize_t">;
2254
+ readonly ATOM: W_WORD;
2255
+ readonly LANGID: W_WORD;
2256
+ readonly COLORREF: W_DWORD;
2257
+ readonly LGRPID: W_DWORD;
2258
+ readonly LCTYPE: W_DWORD;
2259
+ readonly LCID: W_DWORD;
2260
+ readonly HANDLE: W_HANDLE;
2261
+ readonly HACCEL: W_HANDLE;
2262
+ readonly HBITMAP: W_HANDLE;
2263
+ readonly HBRUSH: W_HANDLE;
2264
+ readonly HCOLORSPACE: W_HANDLE;
2265
+ readonly HDC: W_HANDLE;
2266
+ readonly HDESK: W_HANDLE;
2267
+ readonly HDWP: W_HANDLE;
2268
+ readonly HENHMETAFILE: W_HANDLE;
2269
+ readonly HFONT: W_HANDLE;
2270
+ readonly HGDIOBJ: W_HANDLE;
2271
+ readonly HGLOBAL: W_HANDLE;
2272
+ readonly HHOOK: W_HANDLE;
2273
+ readonly HICON: W_HANDLE;
2274
+ readonly HINSTANCE: W_HANDLE;
2275
+ readonly HKEY: W_HANDLE;
2276
+ readonly HKL: W_HANDLE;
2277
+ readonly HLOCAL: W_HANDLE;
2278
+ readonly HMENU: W_HANDLE;
2279
+ readonly HMETAFILE: W_HANDLE;
2280
+ readonly HMODULE: W_HANDLE;
2281
+ readonly HMONITOR: W_HANDLE;
2282
+ readonly HPALETTE: W_HANDLE;
2283
+ readonly HPEN: W_HANDLE;
2284
+ readonly HRGN: W_HANDLE;
2285
+ readonly HRSRC: W_HANDLE;
2286
+ readonly HSTR: W_HANDLE;
2287
+ readonly HTASK: W_HANDLE;
2288
+ readonly HWINSTA: W_HANDLE;
2289
+ readonly HWND: W_HANDLE;
2290
+ readonly SC_HANDLE: W_HANDLE;
2291
+ readonly SERVICE_STATUS_HANDLE: W_HANDLE;
2292
+ readonly RECT: W_RECT;
2293
+ readonly tagRECT: W_RECT;
2294
+ readonly _RECTL: W_RECT;
2295
+ readonly RECTL: W_RECT;
2296
+ readonly _SMALL_RECT: W_SMALL_RECT;
2297
+ readonly SMALL_RECT: W_SMALL_RECT;
2298
+ readonly _COORD: StructureOf<{ X: number; Y: number }>;
2299
+ readonly POINT: W_POINT;
2300
+ readonly tagPOINT: W_POINT;
2301
+ readonly _POINTL: W_POINT;
2302
+ readonly POINTL: W_POINT;
2303
+ readonly SIZE: W_SIZE;
2304
+ readonly tagSIZE: W_SIZE;
2305
+ readonly SIZEL: W_SIZE;
2306
+ /** `red + (green << 8) + (blue << 16)` */
2307
+ RGB(red: number, green: number, blue: number): number;
2308
+ readonly FILETIME: W_FILETIME;
2309
+ readonly _FILETIME: W_FILETIME;
2310
+ readonly MSG: W_MSG;
2311
+ readonly tagMSG: W_MSG;
2312
+ readonly MAX_PATH: 260;
2313
+ readonly WIN32_FIND_DATAA: W_FIND_DATA;
2314
+ readonly WIN32_FIND_DATAW: W_FIND_DATA;
2315
+ readonly LPBOOL: PointerTypeDef<W_LONG>;
2316
+ readonly PBOOL: PointerTypeDef<W_LONG>;
2317
+ readonly PBOOLEAN: PointerTypeDef<W_BYTE>;
2318
+ readonly LPBYTE: PointerTypeDef<W_BYTE>;
2319
+ readonly PBYTE: PointerTypeDef<W_BYTE>;
2320
+ readonly PCHAR: PointerTypeDef<SimpleCDataConstructor<"char">>;
2321
+ readonly LPCOLORREF: PointerTypeDef<W_DWORD>;
2322
+ readonly LPDWORD: PointerTypeDef<W_DWORD>;
2323
+ readonly PDWORD: PointerTypeDef<W_DWORD>;
2324
+ readonly LPFILETIME: PointerTypeDef<W_FILETIME>;
2325
+ readonly PFILETIME: PointerTypeDef<W_FILETIME>;
2326
+ readonly PFLOAT: PointerTypeDef<SimpleCDataConstructor<"float">>;
2327
+ readonly LPHANDLE: PointerTypeDef<W_HANDLE>;
2328
+ readonly PHANDLE: PointerTypeDef<W_HANDLE>;
2329
+ readonly PHKEY: PointerTypeDef<W_HANDLE>;
2330
+ readonly LPHKL: PointerTypeDef<W_HANDLE>;
2331
+ readonly LPINT: PointerTypeDef<SimpleCDataConstructor<"int32">>;
2332
+ readonly PINT: PointerTypeDef<SimpleCDataConstructor<"int32">>;
2333
+ readonly PLARGE_INTEGER: PointerTypeDef<SimpleCDataConstructor<"int64">>;
2334
+ readonly PLCID: PointerTypeDef<W_DWORD>;
2335
+ readonly LPLONG: PointerTypeDef<W_LONG>;
2336
+ readonly PLONG: PointerTypeDef<W_LONG>;
2337
+ readonly LPMSG: PointerTypeDef<W_MSG>;
2338
+ readonly PMSG: PointerTypeDef<W_MSG>;
2339
+ readonly LPPOINT: PointerTypeDef<W_POINT>;
2340
+ readonly PPOINT: PointerTypeDef<W_POINT>;
2341
+ readonly PPOINTL: PointerTypeDef<W_POINT>;
2342
+ readonly LPRECT: PointerTypeDef<W_RECT>;
2343
+ readonly PRECT: PointerTypeDef<W_RECT>;
2344
+ readonly LPRECTL: PointerTypeDef<W_RECT>;
2345
+ readonly PRECTL: PointerTypeDef<W_RECT>;
2346
+ readonly LPSC_HANDLE: PointerTypeDef<W_HANDLE>;
2347
+ readonly PSHORT: PointerTypeDef<W_SHORT>;
2348
+ readonly LPSIZE: PointerTypeDef<W_SIZE>;
2349
+ readonly PSIZE: PointerTypeDef<W_SIZE>;
2350
+ readonly LPSIZEL: PointerTypeDef<W_SIZE>;
2351
+ readonly PSIZEL: PointerTypeDef<W_SIZE>;
2352
+ readonly PSMALL_RECT: PointerTypeDef<W_SMALL_RECT>;
2353
+ readonly LPUINT: PointerTypeDef<SimpleCDataConstructor<"uint32">>;
2354
+ readonly PUINT: PointerTypeDef<SimpleCDataConstructor<"uint32">>;
2355
+ readonly PULARGE_INTEGER: PointerTypeDef<SimpleCDataConstructor<"uint64">>;
2356
+ readonly PULONG: PointerTypeDef<W_DWORD>;
2357
+ readonly PUSHORT: PointerTypeDef<W_WORD>;
2358
+ readonly PWCHAR: PointerTypeDef<SimpleCDataConstructor<"wchar">>;
2359
+ readonly LPWIN32_FIND_DATAA: PointerTypeDef<W_FIND_DATA>;
2360
+ readonly PWIN32_FIND_DATAA: PointerTypeDef<W_FIND_DATA>;
2361
+ readonly LPWIN32_FIND_DATAW: PointerTypeDef<W_FIND_DATA>;
2362
+ readonly PWIN32_FIND_DATAW: PointerTypeDef<W_FIND_DATA>;
2363
+ readonly LPWORD: PointerTypeDef<W_WORD>;
2364
+ readonly PWORD: PointerTypeDef<W_WORD>;
2365
+ // Extras (not in Python's wintypes)
2366
+ readonly QWORD: SimpleCDataConstructor<"uint64">;
2367
+ readonly DWORDLONG: SimpleCDataConstructor<"uint64">;
2368
+ readonly LONGLONG: SimpleCDataConstructor<"int64">;
2369
+ readonly ULONGLONG: SimpleCDataConstructor<"uint64">;
2370
+ readonly PVOID: W_HANDLE;
2371
+ readonly HCURSOR: W_HANDLE;
2372
+ readonly LRESULT: SimpleCDataConstructor<"ssize_t">;
2373
+ readonly UINT_PTR: SimpleCDataConstructor<"size_t">;
2374
+ readonly LONG_PTR: SimpleCDataConstructor<"ssize_t">;
2375
+ readonly ULONG_PTR: SimpleCDataConstructor<"size_t">;
2376
+ readonly LSTATUS: W_LONG;
2377
+ readonly REGSAM: W_DWORD;
2378
+ };
1843
2379
 
1844
2380
  /**
1845
2381
  * Base class for creating custom simple C data types.
@@ -1869,6 +2405,32 @@ export const WCHAR_SIZE: number;
1869
2405
  */
1870
2406
  export const NULL: null;
1871
2407
 
2408
+ /**
2409
+ * Size of `time_t` in bytes. Python: `ctypes.SIZEOF_TIME_T`
2410
+ * @category Constants
2411
+ */
2412
+ export const SIZEOF_TIME_T: number;
2413
+
2414
+ /**
2415
+ * `dlopen` flag: symbols are available to subsequently loaded libraries
2416
+ * (0 on Windows). Python: `ctypes.RTLD_GLOBAL`
2417
+ * @category Constants
2418
+ */
2419
+ export const RTLD_GLOBAL: number;
2420
+
2421
+ /**
2422
+ * `dlopen` flag: symbols stay local to the library (0 on Windows).
2423
+ * Python: `ctypes.RTLD_LOCAL`
2424
+ * @category Constants
2425
+ */
2426
+ export const RTLD_LOCAL: number;
2427
+
2428
+ /**
2429
+ * Default `mode` of {@link CDLL} (`RTLD_LOCAL`). Python: `ctypes.DEFAULT_MODE`
2430
+ * @category Constants
2431
+ */
2432
+ export const DEFAULT_MODE: number;
2433
+
1872
2434
  /**
1873
2435
  * Resolve a library name to a platform-specific filename or path.
1874
2436
  *