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.
@@ -114,7 +114,8 @@ export function _isStruct(type) {
114
114
  * @private
115
115
  */
116
116
  export function _isArrayType(type) {
117
- return typeof type === "object" && type !== null && type._isArrayType === true;
117
+ // I tipi array sono funzioni chiamabili (array(c_int, 3)(1, 2, 3)).
118
+ return (typeof type === "object" || typeof type === "function") && type !== null && type._isArrayType === true;
118
119
  }
119
120
 
120
121
  /**
@@ -135,3 +136,101 @@ export function _isArrayType(type) {
135
136
  export function _isBitField(type) {
136
137
  return typeof type === "object" && type !== null && type._isBitField === true;
137
138
  }
139
+
140
+ /**
141
+ * Address stored by a pointer field assignment: a pointer instance, a
142
+ * CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
143
+ * `null` (NULL) or a Buffer holding an address. Other values are a TypeError,
144
+ * as in Python, instead of a silent NULL.
145
+ *
146
+ * @param {*} value - Assigned value
147
+ * @param {number} pointerSize - Native pointer size
148
+ * @returns {bigint} Address to store
149
+ */
150
+ export function pointerFieldAddress(value, pointerSize) {
151
+ if (typeof value === "bigint") return value;
152
+ if (typeof value === "number") return BigInt(value);
153
+ if (value === null || value === undefined) return 0n;
154
+ if (typeof value === "object") {
155
+ if (typeof value.address === "bigint") return value.address;
156
+ const param = value._as_parameter_;
157
+ if (typeof param === "bigint") return param;
158
+ if (typeof param === "number") return BigInt(param);
159
+ if (Buffer.isBuffer(value)) return pointerSize === 8 ? value.readBigUInt64LE(0) : BigInt(value.readUInt32LE(0));
160
+ }
161
+ throw new TypeError(`incompatible types, ${typeof value === "function" ? "function" : typeof value} instead of pointer`);
162
+ }
163
+
164
+ const funcPtrFieldTypes = new WeakMap();
165
+
166
+ /**
167
+ * Field type for a CFUNCTYPE prototype: a pointer-sized field whose value is
168
+ * the callable function (`null` for NULL), as Python ctypes.
169
+ *
170
+ * @param {Function} prototype - CFUNCTYPE/WINFUNCTYPE type
171
+ * @returns {Object} Pointer-like field type
172
+ */
173
+ export function funcPtrFieldType(prototype) {
174
+ let fieldType = funcPtrFieldTypes.get(prototype);
175
+ if (fieldType === undefined) {
176
+ fieldType = { _pointerTo: prototype, _isFuncPtrField: true, fromAddress: (address) => prototype(address) };
177
+ funcPtrFieldTypes.set(prototype, fieldType);
178
+ }
179
+ return fieldType;
180
+ }
181
+
182
+ /**
183
+ * Keep `value` alive as long as `targetBuf`, like Python ctypes `_objects`:
184
+ * an object whose address is stored in the buffer (pointer, callback) must
185
+ * not be garbage collected while native code can still read that address.
186
+ * Shares the slot table used for c_char_p / c_wchar_p fields.
187
+ *
188
+ * @param {Buffer} targetBuf - Buffer holding the address
189
+ * @param {number} offset - Offset of the slot
190
+ * @param {*} value - Referenced object (or null to clear the slot)
191
+ */
192
+ export function keepAlive(targetBuf, offset, value) {
193
+ let keep = targetBuf.__ctypesKeepalive;
194
+ if (keep === undefined) {
195
+ keep = Object.create(null);
196
+ Object.defineProperty(targetBuf, "__ctypesKeepalive", { value: keep });
197
+ }
198
+ keep[offset] = value !== null && typeof value === "object" ? value : undefined;
199
+ }
200
+
201
+ /**
202
+ * Write a pointer field (struct, union or array element) and keep the
203
+ * assigned object alive with the buffer, as Python ctypes `_objects`.
204
+ *
205
+ * @param {Buffer} buf - Target buffer
206
+ * @param {number} offset - Field offset
207
+ * @param {*} value - Assigned value (see {@link pointerFieldAddress})
208
+ * @param {number} pointerSize - Native pointer size
209
+ */
210
+ export function writePointerField(buf, offset, value, pointerSize) {
211
+ const address = pointerFieldAddress(value, pointerSize);
212
+ if (pointerSize === 8) buf.writeBigUInt64LE(address, offset);
213
+ else buf.writeUInt32LE(Number(address), offset);
214
+ keepAlive(buf, offset, value);
215
+ }
216
+
217
+ /**
218
+ * Copy a struct/union instance into a nested field: the bytes (as Python
219
+ * does) plus the objects it keeps alive (strings, pointers, callbacks), so
220
+ * the addresses copied with them stay valid.
221
+ *
222
+ * @param {Buffer} buf - Target buffer
223
+ * @param {number} offset - Field offset
224
+ * @param {number} size - Field size
225
+ * @param {Object} value - Instance with a `_buffer`
226
+ */
227
+ export function copyInstance(buf, offset, size, value) {
228
+ const source = value._buffer;
229
+ source.copy(buf, offset, 0, size);
230
+ const kept = source.__ctypesKeepalive;
231
+ if (kept !== undefined) {
232
+ for (const key of Object.keys(kept)) {
233
+ if (Number(key) < size) keepAlive(buf, offset + Number(key), kept[key]);
234
+ }
235
+ }
236
+ }
@@ -35,6 +35,7 @@
35
35
 
36
36
  import { _readBitField, _writeBitField } from "./bitfield.js";
37
37
  import { buildWrapper } from "./wrap.js";
38
+ import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
38
39
 
39
40
  /**
40
41
  * Creates a struct type definition with proper alignment and padding.
@@ -83,6 +84,9 @@ import { buildWrapper } from "./wrap.js";
83
84
  * console.log(PackedData.size); // 7 (no padding)
84
85
  * ```
85
86
  */
87
+ // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
88
+ const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fromAddress(address));
89
+
86
90
  export function struct(fields, options = {}, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
87
91
  // Validate inputs
88
92
  if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
@@ -323,7 +327,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
323
327
  }
324
328
  }
325
329
  // Caso 4b: POINTER() type — stored as pointer-sized field with typed access
326
- else if (typeof type === "object" && type !== null && type._pointerTo !== undefined) {
330
+ else if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
327
331
  // Reset bit field state
328
332
  currentBitFieldBase = null;
329
333
  currentBitOffset = 0;
@@ -337,7 +341,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
337
341
 
338
342
  fieldDef = {
339
343
  name,
340
- type,
344
+ // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
345
+ type: typeof type === "function" ? funcPtrFieldType(type) : type,
341
346
  offset: totalSize,
342
347
  size,
343
348
  alignment,
@@ -527,26 +532,14 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
527
532
  const fieldOffset = offset;
528
533
  const ptrType = field.type;
529
534
  if (is64) {
530
- fieldReaders[name] = (buf) => ptrType.fromAddress(buf.readBigUInt64LE(fieldOffset));
535
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset));
531
536
  fieldWriters[name] = (buf, val) => {
532
- let addr;
533
- if (typeof val === "bigint") addr = val;
534
- else if (typeof val === "number") addr = BigInt(val);
535
- else if (val && typeof val.address === "bigint") addr = val.address;
536
- else if (Buffer.isBuffer(val)) addr = val.readBigUInt64LE(0);
537
- else addr = 0n;
538
- buf.writeBigUInt64LE(addr, fieldOffset);
537
+ writePointerField(buf, fieldOffset, val, 8);
539
538
  };
540
539
  } else {
541
- fieldReaders[name] = (buf) => ptrType.fromAddress(BigInt(buf.readUInt32LE(fieldOffset)));
540
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)));
542
541
  fieldWriters[name] = (buf, val) => {
543
- let addr;
544
- if (typeof val === "bigint") addr = val;
545
- else if (typeof val === "number") addr = BigInt(val);
546
- else if (val && typeof val.address === "bigint") addr = val.address;
547
- else if (Buffer.isBuffer(val)) addr = BigInt(val.readUInt32LE(0));
548
- else addr = 0n;
549
- buf.writeUInt32LE(Number(addr), fieldOffset);
542
+ writePointerField(buf, fieldOffset, val, 4);
550
543
  };
551
544
  }
552
545
  continue;
@@ -673,12 +666,13 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
673
666
  // POINTER() field — return PointerInstance
674
667
  if (field.isPointer) {
675
668
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
676
- return field.type.fromAddress(addr);
669
+ return pointerOrNull(field.type, addr);
677
670
  }
678
671
 
679
- // Array field
672
+ // Array field (Python: c_char * n / c_wchar * n si leggono come stringa)
680
673
  if (field.isArray) {
681
674
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
675
+ if (field.type._charKind !== undefined) return field.type.getValue(arrayBuf);
682
676
  return field.type.wrap(arrayBuf);
683
677
  }
684
678
 
@@ -753,6 +747,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
753
747
  if (field.isNested) {
754
748
  if (Buffer.isBuffer(value)) {
755
749
  value.copy(buf, field.offset, 0, field.size);
750
+ } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
751
+ // Istanza struct/union: copia dei byte (Python), non campo per campo
752
+ copyInstance(buf, field.offset, field.size, value);
756
753
  } else if (typeof value === "object") {
757
754
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
758
755
  for (const [k, v] of Object.entries(value)) {
@@ -764,27 +761,15 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
764
761
 
765
762
  // POINTER() field — write address
766
763
  if (field.isPointer) {
767
- let addr;
768
- if (typeof value === "bigint") {
769
- addr = value;
770
- } else if (typeof value === "number") {
771
- addr = BigInt(value);
772
- } else if (value && typeof value.address === "bigint") {
773
- addr = value.address;
774
- } else {
775
- addr = 0n;
776
- }
777
- if (native.POINTER_SIZE === 8) {
778
- buf.writeBigUInt64LE(addr, field.offset);
779
- } else {
780
- buf.writeUInt32LE(Number(addr), field.offset);
781
- }
764
+ writePointerField(buf, field.offset, value, native.POINTER_SIZE);
782
765
  return;
783
766
  }
784
767
 
785
768
  // Array field
786
769
  if (field.isArray) {
787
- if (Buffer.isBuffer(value)) {
770
+ if (field.type._charKind !== undefined && typeof value === "string") {
771
+ field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
772
+ } else if (Buffer.isBuffer(value)) {
788
773
  value.copy(buf, field.offset, 0, field.size);
789
774
  } else if (Array.isArray(value)) {
790
775
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -839,6 +824,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
839
824
  } else if (Buffer.isBuffer(value)) {
840
825
  // Copia buffer
841
826
  value.copy(buf, field.offset, 0, field.size);
827
+ } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
828
+ // Istanza struct/union: copia dei byte (Python), non campo per campo
829
+ copyInstance(buf, field.offset, field.size, value);
842
830
  } else if (typeof value === "object") {
843
831
  // Imposta campi da oggetto
844
832
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -851,7 +839,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
851
839
 
852
840
  // Array field
853
841
  if (field.isArray) {
854
- if (Buffer.isBuffer(value)) {
842
+ if (field.type._charKind !== undefined && typeof value === "string") {
843
+ field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
844
+ } else if (Buffer.isBuffer(value)) {
855
845
  // Copia buffer array
856
846
  value.copy(buf, field.offset, 0, field.size);
857
847
  } else if (Array.isArray(value)) {
@@ -911,10 +901,10 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
911
901
  }
912
902
  } else if (field.isPointer) {
913
903
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
914
- result[field.name] = field.type.fromAddress(addr);
904
+ result[field.name] = pointerOrNull(field.type, addr);
915
905
  } else if (field.isArray) {
916
906
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
917
- result[field.name] = field.type.wrap(arrayBuf);
907
+ result[field.name] = field.type._charKind !== undefined ? field.type.getValue(arrayBuf) : field.type.wrap(arrayBuf);
918
908
  } else {
919
909
  // Tipo base - lettura diretta
920
910
  result[field.name] = readValue(buf, field.type, field.offset);
@@ -36,6 +36,7 @@
36
36
 
37
37
  import { _readBitField, _writeBitField } from "./bitfield.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
+ import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
39
40
 
40
41
  /**
41
42
  * Creates a union type definition where all fields share offset 0.
@@ -86,6 +87,9 @@ import { buildWrapper } from "./wrap.js";
86
87
  * });
87
88
  * ```
88
89
  */
90
+ // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
91
+ const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fromAddress(address));
92
+
89
93
  export function union(fields, options, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
90
94
  // Backward-compat: legacy positional signature (fields, sizeof, alloc, ...)
91
95
  // had `options` missing. Detect that shape and shift arguments.
@@ -142,10 +146,11 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
142
146
  fieldDef.type = type.baseType; // Usa il tipo base per lettura/scrittura
143
147
  }
144
148
  // POINTER() type
145
- else if (typeof type === "object" && type !== null && type._pointerTo !== undefined) {
149
+ else if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
146
150
  size = native.POINTER_SIZE;
147
151
  alignment = Math.min(size, native.POINTER_SIZE);
148
- fieldDef.type = type;
152
+ // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
153
+ fieldDef.type = typeof type === "function" ? funcPtrFieldType(type) : type;
149
154
  fieldDef.isPointer = true;
150
155
  }
151
156
  // Tipo base (SimpleCData)
@@ -281,26 +286,14 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
281
286
  if (field.isPointer) {
282
287
  const ptrType = field.type;
283
288
  if (is64) {
284
- fieldReaders[name] = (buf) => ptrType.fromAddress(buf.readBigUInt64LE(offset));
289
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(offset));
285
290
  fieldWriters[name] = (buf, val) => {
286
- let addr;
287
- if (typeof val === "bigint") addr = val;
288
- else if (typeof val === "number") addr = BigInt(val);
289
- else if (val && typeof val.address === "bigint") addr = val.address;
290
- else if (Buffer.isBuffer(val)) addr = val.readBigUInt64LE(0);
291
- else addr = 0n;
292
- buf.writeBigUInt64LE(addr, offset);
291
+ writePointerField(buf, offset, val, 8);
293
292
  };
294
293
  } else {
295
- fieldReaders[name] = (buf) => ptrType.fromAddress(BigInt(buf.readUInt32LE(offset)));
294
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(offset)));
296
295
  fieldWriters[name] = (buf, val) => {
297
- let addr;
298
- if (typeof val === "bigint") addr = val;
299
- else if (typeof val === "number") addr = BigInt(val);
300
- else if (val && typeof val.address === "bigint") addr = val.address;
301
- else if (Buffer.isBuffer(val)) addr = BigInt(val.readUInt32LE(0));
302
- else addr = 0n;
303
- buf.writeUInt32LE(Number(addr), offset);
296
+ writePointerField(buf, offset, val, 4);
304
297
  };
305
298
  }
306
299
  continue;
@@ -430,15 +423,17 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
430
423
  });
431
424
  }
432
425
 
433
- // Array
426
+ // Array (Python: c_char * n / c_wchar * n si leggono come stringa)
434
427
  if (field.isArray) {
435
- return field.type.wrap(buf.subarray(field.offset, field.offset + field.size));
428
+ const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
429
+ if (field.type._charKind !== undefined) return field.type.getValue(arrayBuf);
430
+ return field.type.wrap(arrayBuf);
436
431
  }
437
432
 
438
433
  // POINTER() field — return PointerInstance
439
434
  if (field.isPointer) {
440
435
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
441
- return field.type.fromAddress(addr);
436
+ return pointerOrNull(field.type, addr);
442
437
  }
443
438
 
444
439
  // Tipo base — BigEndianUnion path when swapped + primitive
@@ -475,6 +470,9 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
475
470
  if (field.isNested) {
476
471
  if (Buffer.isBuffer(value)) {
477
472
  value.copy(buf, field.offset, 0, field.size);
473
+ } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
474
+ // Istanza struct/union: copia dei byte (Python), non campo per campo
475
+ copyInstance(buf, field.offset, field.size, value);
478
476
  } else if (typeof value === "object") {
479
477
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
480
478
  for (const [k, v] of Object.entries(value)) {
@@ -486,7 +484,9 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
486
484
 
487
485
  // Array
488
486
  if (field.isArray) {
489
- if (Buffer.isBuffer(value)) {
487
+ if (field.type._charKind !== undefined && typeof value === "string") {
488
+ field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
489
+ } else if (Buffer.isBuffer(value)) {
490
490
  value.copy(buf, field.offset, 0, field.size);
491
491
  } else if (Array.isArray(value)) {
492
492
  const wrapped = field.type.wrap(buf.subarray(field.offset, field.offset + field.size));
@@ -502,23 +502,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
502
502
 
503
503
  // POINTER() field — write address
504
504
  if (field.isPointer) {
505
- let addr;
506
- if (typeof value === "bigint") {
507
- addr = value;
508
- } else if (typeof value === "number") {
509
- addr = BigInt(value);
510
- } else if (value && typeof value.address === "bigint") {
511
- addr = value.address;
512
- } else if (Buffer.isBuffer(value)) {
513
- addr = native.POINTER_SIZE === 8 ? value.readBigUInt64LE(0) : BigInt(value.readUInt32LE(0));
514
- } else {
515
- addr = 0n;
516
- }
517
- if (native.POINTER_SIZE === 8) {
518
- buf.writeBigUInt64LE(addr, field.offset);
519
- } else {
520
- buf.writeUInt32LE(Number(addr), field.offset);
521
- }
505
+ writePointerField(buf, field.offset, value, native.POINTER_SIZE);
522
506
  return;
523
507
  }
524
508
 
@@ -577,11 +561,12 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
577
561
  }
578
562
  return nestedCache.get(field.name);
579
563
  } else if (field.isArray) {
564
+ if (field.type._charKind !== undefined) return field.type.getValue(buf.subarray(0, field.size));
580
565
  const wrapped = field.type.wrap(buf.subarray(0, field.size));
581
566
  return [...wrapped];
582
567
  } else if (field.isPointer) {
583
568
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(0) : BigInt(buf.readUInt32LE(0));
584
- return field.type.fromAddress(addr);
569
+ return pointerOrNull(field.type, addr);
585
570
  } else if (swapped && typeof field.type === "function" && field.type._isSimpleCData && field.type._readerBE) {
586
571
  return field.type._readerBE(buf, 0);
587
572
  } else {
@@ -592,23 +577,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
592
577
  if (field.isBitField) {
593
578
  _writeBitField(buf, 0, field.type, field.bitOffset, field.bitSize, value, sizeof);
594
579
  } else if (field.isPointer) {
595
- let addr;
596
- if (typeof value === "bigint") {
597
- addr = value;
598
- } else if (typeof value === "number") {
599
- addr = BigInt(value);
600
- } else if (value && typeof value.address === "bigint") {
601
- addr = value.address;
602
- } else if (Buffer.isBuffer(value)) {
603
- addr = native.POINTER_SIZE === 8 ? value.readBigUInt64LE(0) : BigInt(value.readUInt32LE(0));
604
- } else {
605
- addr = 0n;
606
- }
607
- if (native.POINTER_SIZE === 8) {
608
- buf.writeBigUInt64LE(addr, 0);
609
- } else {
610
- buf.writeUInt32LE(Number(addr), 0);
611
- }
580
+ writePointerField(buf, 0, value, native.POINTER_SIZE);
612
581
  } else if (swapped && typeof field.type === "function" && field.type._isSimpleCData && field.type._writerBE) {
613
582
  field.type._writerBE(buf, 0, value);
614
583
  } else {
@@ -233,5 +233,9 @@ export function createSimpleCDataClass(alloc, ptrToBuffer) {
233
233
 
234
234
  SimpleCData._isSimpleCData = true;
235
235
 
236
+ // Marcatore per riconoscere le istanze (es. negli argomenti di funzione) con
237
+ // un semplice accesso a proprietà, senza instanceof né `constructor`.
238
+ Object.defineProperty(SimpleCData.prototype, "_isSimpleCDataInstance", { value: true });
239
+
236
240
  return SimpleCData;
237
241
  }
@@ -41,11 +41,11 @@
41
41
  * ```javascript
42
42
  * import { c_char, c_wchar } from 'node-ctypes';
43
43
  *
44
- * const ch = new c_char('A'.charCodeAt(0));
45
- * console.log(ch.value); // 65
44
+ * const ch = new c_char('A'); // Python: c_char(b'A')
45
+ * console.log(ch.value); // 'A'
46
46
  *
47
47
  * const wide = new c_wchar(0x4E2D); // Chinese character
48
- * console.log(wide.value); // 20013
48
+ * console.log(wide.value); // '中'
49
49
  * ```
50
50
  *
51
51
  * @example Using pointer types
@@ -228,14 +228,37 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
228
228
  // Character types
229
229
  // ============================================================================
230
230
 
231
+ // Python c_char: il valore è un bytes di 1 byte; in JS una stringa di 1
232
+ // carattere con codice 0-255. In scrittura accetta anche un numero o un Buffer.
233
+ // Python ctypes accetta solo un singolo carattere (o un intero 0..255 per c_char).
234
+ const charCode = (val) => {
235
+ if (typeof val === "string") {
236
+ if (val.length === 1 && val.charCodeAt(0) <= 0xff) return val.charCodeAt(0);
237
+ } else if (Buffer.isBuffer(val) || val instanceof Uint8Array) {
238
+ if (val.length === 1) return val[0];
239
+ } else if (typeof val === "number" && Number.isInteger(val) && val >= 0 && val <= 0xff) {
240
+ return val;
241
+ }
242
+ throw new TypeError("one character bytes, bytearray or integer expected");
243
+ };
244
+
245
+ const wcharCode = (val) => {
246
+ if (typeof val === "string") {
247
+ const code = val.codePointAt(0);
248
+ if (code !== undefined && val.length === (code > 0xffff ? 2 : 1)) return code;
249
+ throw new TypeError("one character unicode string expected");
250
+ }
251
+ if (typeof val === "number" && Number.isInteger(val) && val >= 0) return val;
252
+ throw new TypeError(`unicode string expected instead of ${val === null ? "null" : typeof val}`);
253
+ };
254
+
231
255
  class c_char extends SimpleCData {
232
256
  static _size = 1;
233
- static _type = CType.INT8; // char is int8 in C
234
- static _signed = true; // `char` è signed su x86_64/Linux (ABI comune)
235
- static _reader = (buf, off) => buf.readInt8(off);
257
+ static _type = CType.CHAR;
258
+ static _charKind = "char";
259
+ static _reader = (buf, off) => String.fromCharCode(buf.readUInt8(off));
236
260
  static _writer = (buf, off, val) => {
237
- if (typeof val === "string") val = val.charCodeAt(0);
238
- buf.writeInt8(val, off);
261
+ buf.writeUInt8(charCode(val), off);
239
262
  };
240
263
  static _readerBE = c_char._reader;
241
264
  static _writerBE = c_char._writer;
@@ -244,6 +267,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
244
267
  class c_wchar extends SimpleCData {
245
268
  static _size = native.WCHAR_SIZE;
246
269
  static _type = CType.WCHAR;
270
+ static _charKind = "wchar";
247
271
  static _reader = (buf, off) => {
248
272
  if (native.WCHAR_SIZE === 2) {
249
273
  return String.fromCharCode(buf.readUInt16LE(off));
@@ -251,7 +275,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
251
275
  return String.fromCodePoint(buf.readUInt32LE(off));
252
276
  };
253
277
  static _writer = (buf, off, val) => {
254
- const code = typeof val === "string" ? val.codePointAt(0) : val;
278
+ const code = wcharCode(val);
255
279
  if (native.WCHAR_SIZE === 2) {
256
280
  buf.writeUInt16LE(code, off);
257
281
  } else {
@@ -265,7 +289,7 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
265
289
  return String.fromCodePoint(buf.readUInt32BE(off));
266
290
  };
267
291
  static _writerBE = (buf, off, val) => {
268
- const code = typeof val === "string" ? val.codePointAt(0) : val;
292
+ const code = wcharCode(val);
269
293
  if (native.WCHAR_SIZE === 2) {
270
294
  buf.writeUInt16BE(code, off);
271
295
  } else {
@@ -360,22 +384,28 @@ export function createPrimitiveTypes(SimpleCData, native, addressOf, cstring, ws
360
384
  // Get actual long size from native module (4 on Windows, 4 or 8 on Unix depending on arch)
361
385
  const _longSize = native.sizeof ? native.sizeof(CType.LONG) : 4;
362
386
 
387
+ // c_long / c_ulong valgono BigInt su ogni piattaforma, anche dove `long` è a
388
+ // 32 bit (Windows): stesso tipo JS per ritorni, campi e `.value` ovunque.
389
+ // In scrittura accettano number e BigInt (troncato ai bit del tipo, come Python).
390
+ const asInt32 = (val) => (typeof val === "bigint" ? Number(BigInt.asIntN(32, val)) : val);
391
+ const asUint32 = (val) => (typeof val === "bigint" ? Number(BigInt.asUintN(32, val)) : val);
392
+
363
393
  class c_long extends SimpleCData {
364
394
  static _size = _longSize;
365
395
  static _type = CType.LONG;
366
- static _reader = _longSize === 8 ? (buf, off) => buf.readBigInt64LE(off) : (buf, off) => buf.readInt32LE(off);
367
- static _writer = _longSize === 8 ? (buf, off, val) => buf.writeBigInt64LE(BigInt(val), off) : (buf, off, val) => buf.writeInt32LE(val, off);
368
- static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigInt64BE(off) : (buf, off) => buf.readInt32BE(off);
369
- static _writerBE = _longSize === 8 ? (buf, off, val) => buf.writeBigInt64BE(BigInt(val), off) : (buf, off, val) => buf.writeInt32BE(val, off);
396
+ static _reader = _longSize === 8 ? (buf, off) => buf.readBigInt64LE(off) : (buf, off) => BigInt(buf.readInt32LE(off));
397
+ static _writer = _longSize === 8 ? (buf, off, val) => buf.writeBigInt64LE(BigInt(val), off) : (buf, off, val) => buf.writeInt32LE(asInt32(val), off);
398
+ static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigInt64BE(off) : (buf, off) => BigInt(buf.readInt32BE(off));
399
+ static _writerBE = _longSize === 8 ? (buf, off, val) => buf.writeBigInt64BE(BigInt(val), off) : (buf, off, val) => buf.writeInt32BE(asInt32(val), off);
370
400
  }
371
401
 
372
402
  class c_ulong extends SimpleCData {
373
403
  static _size = _longSize;
374
404
  static _type = CType.ULONG;
375
- static _reader = _longSize === 8 ? (buf, off) => buf.readBigUInt64LE(off) : (buf, off) => buf.readUInt32LE(off);
376
- static _writer = _longSize === 8 ? (buf, off, val) => buf.writeBigUInt64LE(BigInt(val), off) : (buf, off, val) => buf.writeUInt32LE(val, off);
377
- static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigUInt64BE(off) : (buf, off) => buf.readUInt32BE(off);
378
- static _writerBE = _longSize === 8 ? (buf, off, val) => buf.writeBigUInt64BE(BigInt(val), off) : (buf, off, val) => buf.writeUInt32BE(val, off);
405
+ static _reader = _longSize === 8 ? (buf, off) => buf.readBigUInt64LE(off) : (buf, off) => BigInt(buf.readUInt32LE(off));
406
+ static _writer = _longSize === 8 ? (buf, off, val) => buf.writeBigUInt64LE(BigInt(val), off) : (buf, off, val) => buf.writeUInt32LE(asUint32(val), off);
407
+ static _readerBE = _longSize === 8 ? (buf, off) => buf.readBigUInt64BE(off) : (buf, off) => BigInt(buf.readUInt32BE(off));
408
+ static _writerBE = _longSize === 8 ? (buf, off, val) => buf.writeBigUInt64BE(BigInt(val), off) : (buf, off, val) => buf.writeUInt32BE(asUint32(val), off);
379
409
  }
380
410
 
381
411
  // ============================================================================
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-ctypes",
3
- "version": "1.14.0",
3
+ "version": "2.1.0",
4
4
  "description": "Python ctypes-like FFI for Node.js using libffi",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",
@@ -30,6 +30,7 @@
30
30
  "rebuild": "cmake-js rebuild --target ctypes",
31
31
  "clean": "cmake-js clean",
32
32
  "generate-ffi-headers": "node third-party/libffi_cmake/generate-headers.js",
33
+ "test:types": "tsc -p tests/types/tsconfig.json",
33
34
  "docs": "typedoc",
34
35
  "docs:serve": "typedoc && npx serve docs"
35
36
  },
@@ -37,7 +38,8 @@
37
38
  "@types/node": "^25.9.9",
38
39
  "cmake-js": "^8.0.0",
39
40
  "node-addon-api": "^8.9.2",
40
- "typedoc": "^0.28.20"
41
+ "typedoc": "^0.28.20",
42
+ "typescript": "~6.0.3"
41
43
  },
42
44
  "engines": {
43
45
  "node": ">=24.0.0"