node-ctypes 1.13.0 → 2.0.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.js CHANGED
@@ -14,14 +14,16 @@
14
14
  * printf('Hello from Node.js!\\n');
15
15
  */
16
16
 
17
- import { existsSync } from "node:fs";
17
+ import { existsSync, readFileSync } from "node:fs";
18
18
  import { createRequire } from "node:module";
19
19
  import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
20
21
 
21
22
  // Import refactored modules
22
23
  import { LRUCache } from "./utils/cache.js";
23
24
  import { _initConstants } from "./platform/constants.js";
24
25
  import { _toNativeType, _toNativeTypes } from "./core/types.js";
26
+ import { createLazyLoader } from "./core/lazy-loader.js";
25
27
  import { callback as createCallback, threadSafeCallback as createThreadSafeCallback } from "./core/callback.js";
26
28
  import { createCFUNCTYPE, createWINFUNCTYPE } from "./core/funcptr.js";
27
29
  import { createLibraryClasses } from "./core/Library.js";
@@ -38,7 +40,7 @@ import {
38
40
  } from "./memory/buffer.js";
39
41
  import { createMemoryOps } from "./memory/operations.js";
40
42
  import { addressOf as _addressOf, byref as _byref, cast as _cast, ptrToBuffer as _ptrToBuffer, POINTER as _POINTER, pointer as _pointer } from "./memory/pointer.js";
41
- import { FormatError as _FormatError, WinError as _WinError } from "./platform/errors.js";
43
+ import { FormatError as _FormatError, WinError as _WinError, ArgumentError } from "./platform/errors.js";
42
44
  import { bitfield as _bitfield, _isStruct, _isArrayType, _isBitField } from "./structures/helpers/common.js";
43
45
  import { array as _array } from "./structures/helpers/array.js";
44
46
  import { _readBitField as _readBitFieldHelper, _writeBitField as _writeBitFieldHelper, _readUintFromBuffer, _writeUintToBuffer } from "./structures/helpers/bitfield.js";
@@ -50,66 +52,53 @@ import { createSimpleCDataClass } from "./types/SimpleCData.js";
50
52
  import { createPrimitiveTypes } from "./types/primitives.js";
51
53
  import { createWinTypes } from "./platform/win_types.js";
52
54
 
53
- /**
54
- * Get the path to the native module, checking multiple possible locations
55
- * @param {string} moduleName - The name of the npm module
56
- * @param {string} nativeFile - The name of the native .node file
57
- * @param {string} config - Build configuration (Release or Debug)
58
- * @returns {string} The absolute path to the native module
59
- */
60
- const getNativeModulePath = (moduleName, nativeFile, config = "Release") => {
61
- const buildPath = (base) => path.join(base, "build", config, nativeFile);
62
-
63
- // Check if running in Electron
64
- if (process.versions?.electron) {
65
- const electronProcess = process;
66
- if (electronProcess.resourcesPath) {
67
- const unpackedPath = path.join(electronProcess.resourcesPath, "app.asar.unpacked", "node_modules", moduleName);
68
- if (existsSync(buildPath(unpackedPath))) {
69
- return buildPath(unpackedPath);
70
- }
71
- }
72
- }
73
-
74
- // Check in current working directory's node_modules
75
- const cwdPath = buildPath(path.join(process.cwd(), "node_modules", moduleName));
76
- if (existsSync(cwdPath)) {
77
- return cwdPath;
55
+ // Linux with musl (Alpine) uses separate binaries: ctypes-linux-<arch>-musl.node.
56
+ // /usr/bin/ldd runs ld-musl there; without it, the process report has no
57
+ // glibcVersionRuntime under musl.
58
+ const isMusl = () => {
59
+ if (process.platform !== "linux") return false;
60
+ try {
61
+ return readFileSync("/usr/bin/ldd", "utf8").includes("musl");
62
+ } catch {
63
+ return !process.report?.getReport?.()?.header?.glibcVersionRuntime;
78
64
  }
65
+ };
79
66
 
80
- // Check local build directory in the project root (useful for local testing)
81
- const localBuildPath = buildPath(process.cwd());
82
- if (existsSync(localBuildPath)) {
83
- return localBuildPath;
67
+ /**
68
+ * Locate the native module: the local build (`ctypes.node`) or the prebuilt
69
+ * binary for this platform, first in this package (independent of
70
+ * `process.cwd()`), then in the legacy locations (Electron resources and the
71
+ * current directory) for bundled applications.
72
+ *
73
+ * @returns {string} Absolute path of the native module
74
+ */
75
+ const findNativeModule = () => {
76
+ // lib/.. — in Electron the .node files are unpacked next to app.asar.
77
+ const asar = `${path.sep}app.asar${path.sep}`;
78
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..").replace(asar, `${path.sep}app.asar.unpacked${path.sep}`);
79
+ const roots = [packageRoot];
80
+ if (process.versions?.electron && process.resourcesPath) {
81
+ roots.push(path.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "node-ctypes"));
84
82
  }
85
-
86
- // Try Debug build as fallback
87
- if (config === "Release") {
88
- try {
89
- return getNativeModulePath(moduleName, nativeFile, "Debug");
90
- } catch (e) {
91
- // Continue to error below
83
+ roots.push(path.join(process.cwd(), "node_modules", "node-ctypes"), process.cwd());
84
+
85
+ let prebuilt;
86
+ const searched = [];
87
+ for (const root of new Set(roots)) {
88
+ for (const config of ["Release", "Debug"]) {
89
+ const local = path.join(root, "build", config, "ctypes.node");
90
+ if (existsSync(local)) return local;
91
+ prebuilt ??= `ctypes-${process.platform}-${process.arch}${isMusl() ? "-musl" : ""}.node`;
92
+ const candidate = path.join(root, "build", config, prebuilt);
93
+ if (existsSync(candidate)) return candidate;
94
+ searched.push(local, candidate);
92
95
  }
93
96
  }
94
-
95
- throw new Error(`Native module "${nativeFile}" not found for "${moduleName}". ` + `Searched in Electron resources, node_modules, and local build.`);
97
+ throw new Error(`node-ctypes: native module not found. Searched:\n ${searched.join("\n ")}`);
96
98
  };
97
99
 
98
- // Load the native module
99
- let nativeModulePath;
100
- try {
101
- nativeModulePath = getNativeModulePath("node-ctypes", `ctypes.node`);
102
- } catch (e) {
103
- try {
104
- const platform = process.platform;
105
- const arch = process.arch;
106
- nativeModulePath = getNativeModulePath("node-ctypes", `ctypes-${platform}-${arch}.node`);
107
- } catch (fallbackError) {
108
- throw new Error(`Failed to load native module: ${e.message}. Fallback also failed: ${fallbackError.message}`);
109
- }
110
- }
111
- const require = createRequire(path.join(process.cwd(), "index.js"));
112
- const native = require(nativeModulePath);
100
+ const require = createRequire(import.meta.url);
101
+ const native = require(findNativeModule());
113
102
 
114
103
  // Initialize platform constants from native module
115
104
  _initConstants(native);
@@ -117,6 +106,20 @@ _initConstants(native);
117
106
  // Re-esporta le classi native
118
107
  const { Version, Library, FFIFunction, Callback, ThreadSafeCallback, StructType, ArrayType, CType } = native;
119
108
 
109
+ // Gli errori di conversione degli argomenti nel nativo sono ctypes.ArgumentError.
110
+ native.setArgumentError(ArgumentError);
111
+
112
+ // Python ctypes parity: anche i callback nativi (CDLL.callback / Library.callback)
113
+ // si passano direttamente come argomento, tramite `_as_parameter_`.
114
+ for (const NativeCallback of [Callback, ThreadSafeCallback]) {
115
+ Object.defineProperty(NativeCallback.prototype, "_as_parameter_", {
116
+ get() {
117
+ return this.pointer;
118
+ },
119
+ configurable: true,
120
+ });
121
+ }
122
+
120
123
  // ============================================================================
121
124
  // Type Normalization Helpers
122
125
  // Now imported from ./core/types.js - see that file for implementation details
@@ -222,13 +225,17 @@ function alignment(type) {
222
225
  return type.alignment;
223
226
  }
224
227
  // ArrayTypeDef
225
- if (typeof type === "object" && type !== null && type._isArrayType) {
228
+ if ((typeof type === "object" || typeof type === "function") && type !== null && type._isArrayType) {
226
229
  return type.getAlignment();
227
230
  }
228
231
  // SimpleCData class — natural alignment = min(size, POINTER_SIZE)
229
232
  if (typeof type === "function" && type._isSimpleCData) {
230
233
  return Math.min(type._size, native.POINTER_SIZE);
231
234
  }
235
+ // POINTER / CFUNCTYPE type
236
+ if ((typeof type === "function" && type._isFuncPtr === true) || (typeof type === "object" && type !== null && type._pointerTo !== undefined)) {
237
+ return native.POINTER_SIZE;
238
+ }
232
239
  throw new TypeError("alignment() argument must be a ctypes type");
233
240
  }
234
241
 
@@ -268,7 +275,7 @@ function POINTER(baseType) {
268
275
  * ```javascript
269
276
  * const x = new c_int32(42);
270
277
  * const p = pointer(x);
271
- * console.log(p.contents); // 42
278
+ * console.log(p.contents.value); // 42
272
279
  * p.contents = 100;
273
280
  * console.log(x.value); // 100
274
281
  * ```
@@ -345,7 +352,7 @@ memoryDeps.Union = Union;
345
352
  * console.log(arr[2]); // 42
346
353
  */
347
354
  function array(elementType, count) {
348
- return _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType);
355
+ return _array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, c_void_p);
349
356
  }
350
357
 
351
358
  // ============================================================================
@@ -385,6 +392,10 @@ function SetLastError(code) {
385
392
  return native.setCapturedLastError(code);
386
393
  }
387
394
 
395
+ // Nomi Python: ctypes.get_last_error() / ctypes.set_last_error().
396
+ const get_last_error = GetLastError;
397
+ const set_last_error = SetLastError;
398
+
388
399
  function FormatError(code) {
389
400
  // Parity Python: se code non specificato, usa lo slot privato
390
401
  // (ctypes.get_last_error()), non il GetLastError() di sistema.
@@ -483,9 +494,29 @@ const {
483
494
  c_ulonglong,
484
495
  } = primitiveTypes;
485
496
 
497
+ // Primitive integrate la cui lettura nativa (CToJS) dà lo stesso valore di
498
+ // `_reader`: readValue(indirizzo, tipo) le legge con native.readValue invece di
499
+ // creare ogni volta un Buffer esterno con ptrToBuffer (~400 ns → ~30 ns).
500
+ memoryDeps.native = native;
501
+ memoryDeps.nativeReadTypes = new Map([c_int8, c_int16, c_int32, c_int64, c_uint8, c_uint16, c_uint32, c_uint64, c_float, c_double].map((t) => [t, t._type]));
502
+
503
+ // Python ctypes: le funzioni ottenute come attributo (libc.strlen) hanno restype c_int.
504
+ FunctionWrapper.defaultRestype = c_int;
505
+
506
+ // Altri nomi Python ctypes: alias deprecati ma ancora usati, costanti di dlopen.
507
+ const ARRAY = (type, length) => array(type, length);
508
+ const c_buffer = (init, size) => create_string_buffer(init, size);
509
+ const c_voidp = c_void_p;
510
+ // time_t è a 64 bit su tutte le piattaforme a 64 bit supportate.
511
+ const c_time_t = c_int64;
512
+ const SIZEOF_TIME_T = 8;
513
+ const { RTLD_GLOBAL, RTLD_LOCAL } = native;
514
+ const DEFAULT_MODE = RTLD_LOCAL;
515
+ const LibraryLoader = createLazyLoader;
516
+
486
517
  // Windows API type aliases (Python ctypes.wintypes parity).
487
518
  // Factory coerente col resto della lib: cattura primitive già create.
488
- const wintypes = createWinTypes(primitiveTypes);
519
+ const wintypes = createWinTypes(primitiveTypes, { Structure, POINTER, array });
489
520
 
490
521
  // HRESULT: c_int32 subclass tagged for OleDLL auto-error-raising.
491
522
  // Python ctypes parity: `from ctypes import HRESULT`.
@@ -502,12 +533,12 @@ class HRESULT extends c_int32 {
502
533
  // Now imported from ./memory/buffer.js - see that file for implementation details
503
534
  // ============================================================================
504
535
 
505
- function create_string_buffer(init) {
506
- return _create_string_buffer(init, native);
536
+ function create_string_buffer(init, size) {
537
+ return _create_string_buffer(init, size);
507
538
  }
508
539
 
509
- function create_unicode_buffer(init) {
510
- return _create_unicode_buffer(init, native);
540
+ function create_unicode_buffer(init, size) {
541
+ return _create_unicode_buffer(init, size, native);
511
542
  }
512
543
 
513
544
  function string_at(address, size) {
@@ -526,7 +557,7 @@ function memmove(dst, src, count) {
526
557
  }
527
558
 
528
559
  function memset(dst, value, count) {
529
- return _memset(dst, value, count);
560
+ return _memset(dst, value, count, native);
530
561
  }
531
562
 
532
563
  // Export come ES module
@@ -592,8 +623,11 @@ export {
592
623
  pointer,
593
624
 
594
625
  // Error handling
626
+ ArgumentError,
595
627
  get_errno,
596
628
  set_errno,
629
+ get_last_error,
630
+ set_last_error,
597
631
  GetLastError,
598
632
  SetLastError,
599
633
  FormatError,
@@ -635,6 +669,16 @@ export {
635
669
  c_ulonglong,
636
670
  // Windows API type aliases (Python ctypes.wintypes parity)
637
671
  wintypes,
672
+ // Altri nomi Python ctypes
673
+ ARRAY,
674
+ c_buffer,
675
+ c_voidp,
676
+ c_time_t,
677
+ SIZEOF_TIME_T,
678
+ RTLD_GLOBAL,
679
+ RTLD_LOCAL,
680
+ DEFAULT_MODE,
681
+ LibraryLoader,
638
682
  };
639
683
 
640
684
  // Re-export constants from platform module
@@ -644,7 +688,6 @@ export { POINTER_SIZE, WCHAR_SIZE, NULL } from "./platform/constants.js";
644
688
  export { find_library } from "./platform/find_library.js";
645
689
 
646
690
  // Lazy loader namespaces (Python's `ctypes.cdll.libname` / `ctypes.windll.libname`).
647
- import { createLazyLoader } from "./core/lazy-loader.js";
648
691
  export const cdll = createLazyLoader(CDLL);
649
692
  export const windll = process.platform === "win32" ? createLazyLoader(WinDLL) : undefined;
650
693
  export const oledll = process.platform === "win32" ? createLazyLoader(OleDLL) : undefined;
@@ -72,6 +72,102 @@ export function alloc(size) {
72
72
  * // H e l l o , ' ' W o r l d ! \0
73
73
  * ```
74
74
  */
75
+ // ----------------------------------------------------------------------------
76
+ // Buffer di caratteri restituiti da create_string_buffer / create_unicode_buffer:
77
+ // restano Buffer di Node, con le proprietà `.value` e `.raw` degli array di
78
+ // c_char / c_wchar di Python. Prototipi condivisi derivati da Buffer.prototype.
79
+ // ----------------------------------------------------------------------------
80
+
81
+ // Stringa senza terminatore in wchar_t (UTF-16LE o UTF-32LE).
82
+ export function encodeWide(str, wcharSize) {
83
+ if (wcharSize === 2) {
84
+ return Buffer.from(str, "utf16le");
85
+ }
86
+ const codePoints = Array.from(str, (ch) => ch.codePointAt(0));
87
+ const buf = Buffer.alloc(codePoints.length * 4);
88
+ codePoints.forEach((cp, i) => buf.writeUInt32LE(cp, i * 4));
89
+ return buf;
90
+ }
91
+
92
+ export function decodeWide(buf, wcharSize) {
93
+ if (wcharSize === 2) {
94
+ let end = 0;
95
+ while (end + 1 < buf.length && buf.readUInt16LE(end) !== 0) end += 2;
96
+ return buf.toString("utf16le", 0, end);
97
+ }
98
+ let out = "";
99
+ for (let off = 0; off + 3 < buf.length; off += 4) {
100
+ const cp = buf.readUInt32LE(off);
101
+ if (cp === 0) break;
102
+ out += String.fromCodePoint(cp);
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // Python: assegnare .value copia i byte e aggiunge il terminatore se c'è spazio;
108
+ // assegnare .raw copia i byte senza terminatore. Più lungo del buffer → errore.
109
+ function assignChars(buf, bytes, terminate, message) {
110
+ if (bytes.length > buf.length) {
111
+ throw new RangeError(message);
112
+ }
113
+ bytes.copy(buf);
114
+ if (terminate && bytes.length < buf.length) {
115
+ buf[bytes.length] = 0;
116
+ }
117
+ }
118
+
119
+ const toBytes = (value) => (Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8"));
120
+
121
+ // Sottoclassi di Uint8Array con prototipo agganciato a Buffer.prototype, come
122
+ // il FastBuffer interno di Node: instanceof Buffer / Buffer.isBuffer restano
123
+ // veri e l'allocazione non passa da Object.setPrototypeOf. Le classi sono
124
+ // dichiarate con il loro nome: ridefinire `name` dopo rallenta `new` in V8.
125
+ function makeBufferClass(BufferClass, properties) {
126
+ Object.setPrototypeOf(BufferClass.prototype, Buffer.prototype);
127
+ Object.defineProperties(BufferClass.prototype, properties);
128
+ return BufferClass;
129
+ }
130
+
131
+ const CharBuffer = makeBufferClass(class CharBuffer extends Uint8Array {}, {
132
+ value: {
133
+ get() {
134
+ const end = this.indexOf(0);
135
+ return this.toString("utf8", 0, end === -1 ? this.length : end);
136
+ },
137
+ set(value) {
138
+ assignChars(this, toBytes(value), true, "byte string too long");
139
+ },
140
+ },
141
+ raw: {
142
+ get() {
143
+ return Buffer.from(this);
144
+ },
145
+ set(value) {
146
+ assignChars(this, toBytes(value), false, "byte string too long");
147
+ },
148
+ },
149
+ });
150
+
151
+ function makeWideBufferClass(wcharSize) {
152
+ return makeBufferClass(class WideBuffer extends Uint8Array {}, {
153
+ value: {
154
+ get() {
155
+ return decodeWide(this, wcharSize);
156
+ },
157
+ set(value) {
158
+ const units = encodeWide(String(value), wcharSize);
159
+ assignChars(this, units, false, "string too long");
160
+ if (units.length + wcharSize <= this.length) {
161
+ this.fill(0, units.length, units.length + wcharSize);
162
+ }
163
+ },
164
+ },
165
+ });
166
+ }
167
+
168
+ const WideBuffer2 = makeWideBufferClass(2);
169
+ const WideBuffer4 = makeWideBufferClass(4);
170
+
75
171
  export function cstring(str, native) {
76
172
  return native.cstring(str);
77
173
  }
@@ -142,14 +238,18 @@ export function wstring(str, native) {
142
238
  * - `create_string_buffer(size)` - Allocates empty buffer of size bytes
143
239
  * - `create_string_buffer(string)` - Creates buffer from string (with null terminator)
144
240
  * - `create_string_buffer(bytes)` - Copies buffer and adds null terminator
241
+ * - `create_string_buffer(init, size)` - Buffer of `size` bytes initialized with `init`
145
242
  *
146
243
  * **Python ctypes Compatibility**:
147
- * Direct equivalent to Python's `ctypes.create_string_buffer()`.
244
+ * Direct equivalent to Python's `ctypes.create_string_buffer()`. The result is a
245
+ * Node Buffer with Python's `.value` (string up to the first NUL) and `.raw`
246
+ * (copy of all bytes) properties, both assignable.
148
247
  *
149
248
  * @param {number|string|Buffer} init - Size, string, or buffer to copy
150
- * @param {Object} native - Native module reference
249
+ * @param {number} [size] - Buffer size in bytes (default: length of `init` + 1)
151
250
  * @returns {Buffer} Created buffer
152
251
  * @throws {TypeError} If init is not number, string, or Buffer
252
+ * @throws {RangeError} If `init` is longer than `size`
153
253
  *
154
254
  * @example Empty buffer
155
255
  * ```javascript
@@ -172,22 +272,29 @@ export function wstring(str, native) {
172
272
  * // Buffer: [72, 101, 108, 108, 111, 0] (adds null terminator)
173
273
  * ```
174
274
  */
175
- export function create_string_buffer(init, native) {
275
+ export function create_string_buffer(init, size) {
276
+ let bytes = null;
176
277
  if (typeof init === "number") {
177
- // create_string_buffer(size) - allocate empty buffer
178
- return alloc(init);
278
+ size = init;
179
279
  } else if (typeof init === "string") {
180
- // create_string_buffer("string") - create buffer with string
181
- return cstring(init, native);
280
+ bytes = Buffer.from(init, "utf8");
182
281
  } else if (Buffer.isBuffer(init)) {
183
- // create_string_buffer(bytes) - copy bytes and add null terminator
184
- const buf = alloc(init.length + 1);
185
- init.copy(buf);
186
- buf[init.length] = 0; // null terminator
187
- return buf;
282
+ bytes = init;
283
+ } else {
284
+ throw new TypeError("create_string_buffer requires number, string, or Buffer");
188
285
  }
189
-
190
- throw new TypeError("create_string_buffer requires number, string, or Buffer");
286
+ if (bytes !== null) {
287
+ if (size === undefined) {
288
+ size = bytes.length + 1;
289
+ } else if (bytes.length > size) {
290
+ throw new RangeError("byte string too long");
291
+ }
292
+ }
293
+ const buf = new CharBuffer(size);
294
+ if (bytes !== null) {
295
+ bytes.copy(buf);
296
+ }
297
+ return buf;
191
298
  }
192
299
 
193
300
  /**
@@ -205,9 +312,11 @@ export function create_string_buffer(init, native) {
205
312
  * Direct equivalent to Python's `ctypes.create_unicode_buffer()`.
206
313
  *
207
314
  * @param {number|string} init - Size in characters or string
315
+ * @param {number} [size] - Buffer size in characters (default: length of `init` + 1)
208
316
  * @param {Object} native - Native module reference (provides WCHAR_SIZE)
209
- * @returns {Buffer} Created wide string buffer
317
+ * @returns {Buffer} Created wide string buffer, with Python's `.value` property
210
318
  * @throws {TypeError} If init is not number or string
319
+ * @throws {RangeError} If `init` is longer than `size`
211
320
  *
212
321
  * @example Empty wide buffer
213
322
  * ```javascript
@@ -228,18 +337,29 @@ export function create_string_buffer(init, native) {
228
337
  * // Wide string buffer with "Hello\0"
229
338
  * ```
230
339
  */
231
- export function create_unicode_buffer(init, native) {
340
+ export function create_unicode_buffer(init, size, native) {
232
341
  const wcharSize = native.WCHAR_SIZE;
233
-
342
+ let units = null;
234
343
  if (typeof init === "number") {
235
- // create_unicode_buffer(size) - allocate empty buffer for N characters
236
- return alloc(init * wcharSize);
344
+ size = init;
237
345
  } else if (typeof init === "string") {
238
- // create_unicode_buffer("string") - create buffer with wide string
239
- return wstring(init, native);
346
+ units = encodeWide(init, wcharSize);
347
+ } else {
348
+ throw new TypeError("create_unicode_buffer requires number or string");
240
349
  }
241
-
242
- throw new TypeError("create_unicode_buffer requires number or string");
350
+ if (units !== null) {
351
+ const count = units.length / wcharSize;
352
+ if (size === undefined) {
353
+ size = count + 1;
354
+ } else if (count > size) {
355
+ throw new RangeError("string too long");
356
+ }
357
+ }
358
+ const buf = wcharSize === 2 ? new WideBuffer2(size * 2) : new WideBuffer4(size * 4);
359
+ if (units !== null) {
360
+ units.copy(buf);
361
+ }
362
+ return buf;
243
363
  }
244
364
 
245
365
  /**
@@ -301,42 +421,7 @@ export function wstring_at(address, size, native) {
301
421
  if (address === null || address === undefined) {
302
422
  return null;
303
423
  }
304
-
305
- const wcharSize = native.WCHAR_SIZE;
306
- let buf;
307
-
308
- if (Buffer.isBuffer(address)) {
309
- buf = address;
310
- } else {
311
- // Convert BigInt/number to buffer
312
- const maxBytes = size ? size * wcharSize : 1024;
313
- buf = native.ptrToBuffer(address, maxBytes);
314
- }
315
-
316
- // Windows: UTF-16LE
317
- if (wcharSize === 2) {
318
- if (size !== undefined) {
319
- return buf.toString("utf16le", 0, size * 2);
320
- }
321
- // Read until null terminator
322
- let end = 0;
323
- while (end < buf.length - 1 && (buf[end] !== 0 || buf[end + 1] !== 0)) {
324
- end += 2;
325
- }
326
- return buf.toString("utf16le", 0, end);
327
- }
328
-
329
- // Unix: UTF-32LE
330
- const chars = [];
331
- const limit = size !== undefined ? size : Math.floor(buf.length / 4);
332
-
333
- for (let i = 0; i < limit; i++) {
334
- const codePoint = buf.readUInt32LE(i * 4);
335
- if (codePoint === 0) break;
336
- chars.push(String.fromCodePoint(codePoint));
337
- }
338
-
339
- return chars.join("");
424
+ return native.readWString(address, size);
340
425
  }
341
426
 
342
427
  /**
@@ -362,18 +447,23 @@ export function wstring_at(address, size, native) {
362
447
  * ```
363
448
  */
364
449
  export function memmove(dst, src, count, native) {
365
- if (!Buffer.isBuffer(dst)) {
366
- throw new TypeError("dst must be a Buffer");
367
- }
450
+ const srcBuf = memoryOf(src, count, native, "src");
451
+ srcBuf.copy(memoryOf(dst, count, native, "dst"), 0, 0, count);
452
+ }
368
453
 
369
- let srcBuf;
370
- if (Buffer.isBuffer(src)) {
371
- srcBuf = src;
372
- } else {
373
- srcBuf = native.ptrToBuffer(src, count);
454
+ // Memoria di un argomento di memmove/memset, come Python: Buffer, istanze
455
+ // ctypes (struct, array, c_*), puntatori o un indirizzo (BigInt/number).
456
+ function memoryOf(value, count, native, name) {
457
+ if (value !== null && typeof value === "object") {
458
+ if (Buffer.isBuffer(value._buffer)) return value._buffer;
459
+ if (value._pointerType !== undefined) return native.ptrToBuffer(value.address, count);
460
+ if (value instanceof Uint8Array) return value;
374
461
  }
375
-
376
- srcBuf.copy(dst, 0, 0, count);
462
+ if (typeof value === "bigint" || typeof value === "number") {
463
+ if (!value) throw new TypeError(`${name} is a NULL pointer`);
464
+ return native.ptrToBuffer(value, count);
465
+ }
466
+ throw new TypeError(`${name} must be a Buffer, a ctypes instance, a pointer or an address`);
377
467
  }
378
468
 
379
469
  /**
@@ -396,9 +486,6 @@ export function memmove(dst, src, count, native) {
396
486
  * console.log([...buf]); // [255, 255, 255, 255, 255, 0, 0, 0, 0, 0]
397
487
  * ```
398
488
  */
399
- export function memset(dst, value, count) {
400
- if (!Buffer.isBuffer(dst)) {
401
- throw new TypeError("dst must be a Buffer");
402
- }
403
- dst.fill(value, 0, count);
489
+ export function memset(dst, value, count, native) {
490
+ memoryOf(dst, count, native, "dst").fill(value, 0, count);
404
491
  }