node-ctypes 2.2.0 → 2.3.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.
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * This module provides the `Structure` base class that users extend to create
7
7
  * custom struct types with automatic field management, memory layout, and
8
- * proxy-based field access.
8
+ * field accessors on the class prototype (as Python field descriptors).
9
9
  *
10
10
  * **Python ctypes Compatibility**:
11
11
  * Direct equivalent to Python's `ctypes.Structure` class with `_fields_` attribute.
@@ -65,6 +65,7 @@
65
65
  */
66
66
 
67
67
  import { kMirrorBase, mirrorBase, mirroredAccessors, mirrorsActive } from "../memory/mirror.js";
68
+ import { fieldsOf } from "./helpers/common.js";
68
69
 
69
70
  /**
70
71
  * Creates the Structure base class with required dependencies injected.
@@ -75,128 +76,135 @@ import { kMirrorBase, mirrorBase, mirroredAccessors, mirrorsActive } from "../me
75
76
  * @returns {Class} Structure base class
76
77
  * @private
77
78
  */
79
+ function isPlainObject(value) {
80
+ const proto = Object.getPrototypeOf(value);
81
+ return proto === Object.prototype || proto === null;
82
+ }
83
+
84
+ // Sorgente di from_buffer / from_buffer_copy (Python: ValueError per offset
85
+ // negativi e sorgenti troppo piccole): Buffer, TypedArray/DataView o istanza
86
+ // ctypes, come per gli array.
87
+ function sourceBytes(source, offset, size, name) {
88
+ const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
89
+ if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
90
+ if (!Number.isInteger(offset)) throw new TypeError(`${name}: offset must be an integer`);
91
+ if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
92
+ if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
93
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
94
+ }
95
+
78
96
  export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
79
97
  // Buffer dell'istanza, letto dall'handler condiviso. Chiave privata e non
80
98
  // `__buffer`, così riassegnare `__buffer` non cambia i campi (come prima).
81
99
  const kBuffer = Symbol("buffer");
100
+ // Definizione (layout) propria di ogni classe, vedi `static get _structDef`.
101
+ const kStructDef = Symbol("structDef");
102
+
103
+ // Definizione con cui è stata creata l'istanza (layout dei suoi byte).
104
+ const kDef = Symbol("def");
105
+ // Istanze dei campi struct/union annidati, create al primo accesso: sono
106
+ // viste sulla memoria dell'istanza, quindi restano valide.
107
+ const kViews = Symbol("views");
108
+ // Nomi dei campi con un accessor installato da noi, per prototipo.
109
+ const installedNames = new WeakMap();
110
+ // Nomi che restano proprietà della libreria anche se usati come campi.
111
+ const reservedNames = new Set(["constructor", "_buffer", "__buffer", "_structDef", "__structDef"]);
112
+
113
+ // Percorso generale di un campo: istanza con un'altra definizione (creata
114
+ // prima di un'invalidazione del layout), copia di memoria nativa (Electron,
115
+ // memory/mirror.js), campi senza lettore precompilato (struct annidate,
116
+ // array, sotto-campi di _anonymous_).
117
+ function readField(inst, name) {
118
+ const def = inst[kDef];
119
+ const base = inst[kMirrorBase];
120
+ const read = (base !== undefined ? mirroredAccessors(def) : def).fieldReaders?.[name];
121
+ return read !== undefined ? read(inst[kBuffer], base) : def.get(inst[kBuffer], name);
122
+ }
82
123
 
83
- // Un handler Proxy per definizione, condiviso da tutte le istanze: prima
84
- // ogni `new` ricreava l'handler (5 closure) e la mappa dei nomi dei campi.
85
- const handlerCache = new WeakMap();
86
- // Istanze su una copia di memoria nativa (Electron, memory/mirror.js):
87
- // stesso handler con lettori e scrittori che sincronizzano il campo.
88
- const mirroredHandlerCache = new WeakMap();
89
-
90
- function getProxyHandler(def, mirrored = false) {
91
- const cache = mirrored ? mirroredHandlerCache : handlerCache;
92
- let handler = cache.get(def);
93
- if (handler !== undefined) return handler;
94
-
95
- // Lookup plana dei nomi (normali + sotto-campi anonymous) su oggetto
96
- // null-proto: bracket access è inline-cached da V8 (più veloce di
97
- // Map.has / Set.has che sono builtin megamorfici).
98
- const allFieldNames = Object.create(null);
124
+ function writeField(inst, name, value) {
125
+ const def = inst[kDef];
126
+ const base = inst[kMirrorBase];
127
+ const write = (base !== undefined ? mirroredAccessors(def) : def).fieldWriters?.[name];
128
+ if (write !== undefined) write(inst[kBuffer], value, base);
129
+ else def.set(inst[kBuffer], name, value);
130
+ }
131
+
132
+ // Python: i campi sono descrittori della classe (CField), non attributi
133
+ // dell'istanza. Qui accessor sul prototipo della classe, condivisi da tutte
134
+ // le istanze: un Proxy per istanza costava ~20 ns per accesso. Il percorso
135
+ // veloce usa il lettore/scrittore precompilato della definizione della classe.
136
+ function installFieldAccessors(Ctor, def) {
137
+ const proto = Ctor.prototype;
138
+ for (const name of installedNames.get(proto) ?? []) {
139
+ delete proto[name];
140
+ }
141
+ const names = [];
99
142
  for (const field of def.fields) {
100
- allFieldNames[field.name] = true;
143
+ names.push(field.name);
101
144
  if (field.isAnonymous && field.type && Array.isArray(field.type.fields)) {
102
- for (const subField of field.type.fields) {
103
- allFieldNames[subField.name] = true;
104
- }
145
+ // Campi promossi (anche da campi anonimi annidati), come Python.
146
+ for (const subField of field.type.fields) names.push(subField.name);
147
+ for (const name of Object.keys(field.type.anonymousFieldNames ?? {})) names.push(name);
105
148
  }
106
149
  }
107
-
108
- // Pre-compiled reader/writer maps from structDef for FAST PATH
109
- // (avoids going through def.get/def.set branching on every access)
110
- const { fieldReaders: readers, fieldWriters: writers } = mirrored ? mirroredAccessors(def) : def;
111
-
112
- handler = {
113
- get(target, prop, receiver) {
114
- // FAST PATH: pre-compiled reader (simple scalar / pointer fields).
115
- // `readers` può essere undefined quando questa Structure è in realtà
116
- // una Union (unionDef non espone fieldReaders al livello esterno).
117
- if (typeof prop === "string") {
118
- const reader = readers !== undefined ? readers[prop] : undefined;
119
- if (reader !== undefined) return reader(target[kBuffer], target[kMirrorBase]);
120
- if (allFieldNames[prop] === true) return def.get(target[kBuffer], prop);
121
- }
122
-
123
- // SLOW PATH: special properties and methods
124
- if (typeof prop === "symbol") {
125
- if (prop === Symbol.toStringTag) return target.constructor.name || "Structure";
126
- return undefined;
127
- }
128
-
129
- if (prop === "_buffer" || prop === "__buffer") return target[kBuffer];
130
- if (prop === "_structDef" || prop === "__structDef") return def;
131
- // La classe, non una sua copia legata (x.constructor === Point).
132
- if (prop === "constructor") return target.constructor;
133
-
134
- const method = target[prop];
135
- if (typeof method === "function") {
136
- // Bind al Proxy (receiver), NON al target raw. Un metodo custom
137
- // come `mag2() { return this.x * this.x + ... }` dentro fa
138
- // `this.x` che deve passare attraverso il Proxy get trap per
139
- // leggere il field. Binding su `target` (istanza raw) salta
140
- // il trap e ritorna undefined → NaN nei calcoli.
141
- return method.bind(receiver);
142
- }
143
-
144
- return Reflect.get(target, prop, receiver);
145
- },
146
- set(target, prop, value, receiver) {
147
- // FAST PATH: pre-compiled writer (null-proto obj, bracket access)
148
- if (typeof prop === "string") {
149
- const writer = writers !== undefined ? writers[prop] : undefined;
150
- if (writer !== undefined) {
151
- writer(target[kBuffer], value, target[kMirrorBase]);
152
- return true;
153
- }
154
- if (allFieldNames[prop] === true) {
155
- def.set(target[kBuffer], prop, value);
156
- return true;
157
- }
158
- }
159
-
160
- return Reflect.set(target, prop, value, receiver);
161
- },
162
- has(target, prop) {
163
- if (typeof prop === "string" && allFieldNames[prop] === true) return true;
164
- if (prop === "_buffer" || prop === "_structDef" || prop === "toObject") return true;
165
- return Reflect.has(target, prop);
166
- },
167
- ownKeys(target) {
168
- const keys = [];
169
- for (const f of def.fields) {
170
- if (f.isAnonymous && f.type && Array.isArray(f.type.fields)) {
171
- for (const sf of f.type.fields) {
172
- keys.push(sf.name);
150
+ const installed = [];
151
+ const nestedClasses = new Map();
152
+ for (const field of def.fields) {
153
+ if (field.isNested && !field.isAnonymous && field.cls !== undefined) nestedClasses.set(field.name, field);
154
+ }
155
+ for (const name of names) {
156
+ if (reservedNames.has(name)) continue;
157
+ const nested = nestedClasses.get(name);
158
+ if (nested !== undefined) {
159
+ const { cls, offset, size } = nested;
160
+ Object.defineProperty(proto, name, {
161
+ get() {
162
+ if (this[kDef] !== def) return readField(this, name);
163
+ let views = this[kViews];
164
+ if (views === undefined) views = this[kViews] = new Map();
165
+ let view = views.get(name);
166
+ if (view === undefined) {
167
+ view = new cls(this[kBuffer].subarray(offset, offset + size));
168
+ views.set(name, view);
173
169
  }
174
- } else {
175
- keys.push(f.name);
176
- }
177
- }
178
- return keys;
179
- },
180
- getOwnPropertyDescriptor(target, prop) {
181
- if (typeof prop === "string" && allFieldNames[prop] === true) {
182
- return {
183
- enumerable: true,
184
- configurable: true,
185
- writable: true,
186
- };
187
- }
188
- if (prop === "_buffer" || prop === "_structDef") {
189
- return {
190
- enumerable: false,
191
- configurable: true,
192
- writable: true,
193
- };
194
- }
195
- return Reflect.getOwnPropertyDescriptor(target, prop);
196
- },
197
- };
198
- cache.set(def, handler);
199
- return handler;
170
+ return view;
171
+ },
172
+ set(value) {
173
+ writeField(this, name, value);
174
+ },
175
+ enumerable: false,
176
+ configurable: true,
177
+ });
178
+ installed.push(name);
179
+ continue;
180
+ }
181
+ const read = def.fieldReaders?.[name];
182
+ const write = def.fieldWriters?.[name];
183
+ Object.defineProperty(proto, name, {
184
+ get:
185
+ read !== undefined
186
+ ? function () {
187
+ if (this[kDef] === def && this[kMirrorBase] === undefined) return read(this[kBuffer]);
188
+ return readField(this, name);
189
+ }
190
+ : function () {
191
+ return readField(this, name);
192
+ },
193
+ set:
194
+ write !== undefined
195
+ ? function (value) {
196
+ if (this[kDef] === def && this[kMirrorBase] === undefined) write(this[kBuffer], value);
197
+ else writeField(this, name, value);
198
+ }
199
+ : function (value) {
200
+ writeField(this, name, value);
201
+ },
202
+ enumerable: false,
203
+ configurable: true,
204
+ });
205
+ installed.push(name);
206
+ }
207
+ installedNames.set(proto, installed);
200
208
  }
201
209
 
202
210
  // Scrittore precompilato del campo quando esiste, altrimenti def.set generico.
@@ -224,12 +232,12 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
224
232
  * Structure base class for creating C-style structures.
225
233
  *
226
234
  * Users extend this class and define static `_fields_` to specify the struct layout.
227
- * The constructor handles memory allocation, field initialization, and returns a
228
- * Proxy for transparent field access.
235
+ * The constructor handles memory allocation and field initialization; the
236
+ * fields are accessors of the class prototype (Python: field descriptors).
229
237
  *
230
238
  * **Key Features**:
231
239
  * - Automatic memory layout based on `_fields_`
232
- * - Proxy-based transparent field access
240
+ * - Field accessors shared by all instances of the class
233
241
  * - Support for positional arguments in constructor
234
242
  * - Buffer wrapping for zero-copy operations
235
243
  * - Anonymous field support via `_anonymous_`
@@ -285,14 +293,19 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
285
293
  class Structure {
286
294
  constructor(...args) {
287
295
  const Ctor = this.constructor;
288
- const def = Ctor._structDef || Ctor._buildStruct();
296
+ // Definizione propria della classe (percorso caldo di `new`: una lettura
297
+ // di proprietà invece di Object.hasOwn).
298
+ const own = Ctor[kStructDef];
299
+ const def = own !== undefined && own.owner === Ctor ? own.def : Ctor._buildStruct();
289
300
  let buf;
290
301
 
291
302
  // Support positional args: new Point(10,20)
292
303
  // Un'istanza di struct/union come unico argomento è posizionale
293
304
  // (Python: RECT(point)), non un oggetto di inizializzazione per nome.
294
305
  const single = args.length === 1 ? args[0] : undefined;
295
- const isNamedInit = typeof single === "object" && single !== null && !Array.isArray(single) && !Buffer.isBuffer(single) && single._structDef === undefined;
306
+ // Solo un oggetto semplice è un'inizializzazione per nome: istanze
307
+ // ctypes (anche SimpleCData, Python: P(c_int(5))) sono posizionali.
308
+ const isNamedInit = typeof single === "object" && single !== null && isPlainObject(single);
296
309
  if (isNamedInit) {
297
310
  // alloc() restituisce un buffer già azzerato (Buffer.alloc)
298
311
  buf = alloc(def.size);
@@ -312,21 +325,54 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
312
325
  if (args.length > 0) {
313
326
  // Positional mapping to non-anonymous declared fields order
314
327
  const ordered = getPositionalFields(def);
315
- for (let i = 0; i < Math.min(args.length, ordered.length); i++) {
328
+ if (args.length > ordered.length) throw new TypeError("too many initializers");
329
+ for (let i = 0; i < args.length; i++) {
316
330
  setField(def, buf, ordered[i].name, args[i]);
317
331
  }
318
332
  }
319
333
  }
320
334
 
321
- // Store internal references on this (needed for methods like toObject)
322
- this.__buffer = buf;
323
- this.__structDef = def;
324
335
  this[kBuffer] = buf;
336
+ this[kDef] = def;
337
+ this[kViews] = undefined;
325
338
  // Indirizzo di una copia di memoria nativa (Electron), undefined altrimenti.
326
- const base = mirrorsActive ? mirrorBase(buf) : undefined;
327
- this[kMirrorBase] = base;
339
+ this[kMirrorBase] = mirrorsActive ? mirrorBase(buf) : undefined;
340
+ }
341
+
342
+ // Memoria e definizione dell'istanza. Riassegnare `__buffer` crea una
343
+ // proprietà propria e non cambia la memoria dei campi.
344
+ get _buffer() {
345
+ return this[kBuffer];
346
+ }
347
+
348
+ get __buffer() {
349
+ return this[kBuffer];
350
+ }
328
351
 
329
- return new Proxy(this, getProxyHandler(def, base !== undefined));
352
+ set __buffer(value) {
353
+ Object.defineProperty(this, "__buffer", { value, writable: true, configurable: true });
354
+ }
355
+
356
+ get _structDef() {
357
+ return this[kDef];
358
+ }
359
+
360
+ get __structDef() {
361
+ return this[kDef];
362
+ }
363
+
364
+ get [Symbol.toStringTag]() {
365
+ return this.constructor.name || "Structure";
366
+ }
367
+
368
+ // I campi non sono proprietà proprie (come in Python): JSON.stringify e
369
+ // util.inspect li mostrano tramite toObject().
370
+ toJSON() {
371
+ return this.toObject();
372
+ }
373
+
374
+ [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
375
+ return `${this.constructor.name || "Structure"} ${inspect(this.toObject(), options)}`;
330
376
  }
331
377
 
332
378
  // Static getters for size, alignment, and fields (enables use as nested type)
@@ -361,14 +407,10 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
361
407
  * @returns {Structure} A new instance sharing memory with source.
362
408
  */
363
409
  static from_buffer(source, offset = 0) {
364
- if (!Buffer.isBuffer(source)) {
365
- throw new TypeError("from_buffer: source must be a Buffer");
366
- }
367
410
  const def = this._structDef || this._buildStruct();
368
- if (source.length - offset < def.size) {
369
- throw new RangeError(`from_buffer: source too small (${source.length - offset} < ${def.size})`);
370
- }
371
- return new this(source.subarray(offset, offset + def.size));
411
+ const bytes = sourceBytes(source, offset, def.size, "from_buffer");
412
+ // Buffer: subarray (conserva la sincronizzazione delle copie native).
413
+ return new this(Buffer.isBuffer(bytes) ? bytes.subarray(offset, offset + def.size) : Buffer.from(bytes.buffer, bytes.byteOffset + offset, def.size));
372
414
  }
373
415
 
374
416
  /**
@@ -379,22 +421,13 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
379
421
  *
380
422
  * @param {Buffer|Uint8Array} source - Bytes to copy from.
381
423
  * @param {number} [offset=0] - Byte offset into source.
382
- * @returns {Structure} A new instance with an independent buffer.
424
+ * @returns {Structure} A new instance with its own buffer.
383
425
  */
384
426
  static from_buffer_copy(source, offset = 0) {
385
- if (!Buffer.isBuffer(source) && !(source instanceof Uint8Array)) {
386
- throw new TypeError("from_buffer_copy: source must be a Buffer or Uint8Array");
387
- }
388
427
  const def = this._structDef || this._buildStruct();
389
- if (source.length - offset < def.size) {
390
- throw new RangeError(`from_buffer_copy: source too small (${source.length - offset} < ${def.size})`);
391
- }
428
+ const bytes = sourceBytes(source, offset, def.size, "from_buffer_copy");
392
429
  const copy = Buffer.alloc(def.size);
393
- if (Buffer.isBuffer(source)) {
394
- source.copy(copy, 0, offset, offset + def.size);
395
- } else {
396
- copy.set(source.subarray(offset, offset + def.size));
397
- }
430
+ copy.set(bytes.subarray(offset, offset + def.size));
398
431
  return new this(copy);
399
432
  }
400
433
 
@@ -410,7 +443,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
410
443
  */
411
444
  static from_address(address) {
412
445
  if (!ptrToBuffer) {
413
- throw new Error("from_address requires the native module (ptrToBuffer unavailable)");
446
+ throw new Error("from_address requires the native module (not loaded)");
414
447
  }
415
448
  const addr = typeof address === "bigint" ? address : BigInt(address);
416
449
  const def = this._structDef || this._buildStruct();
@@ -435,45 +468,72 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
435
468
  }
436
469
 
437
470
  // Build the underlying struct definition and cache it on the constructor
438
- static _buildStruct() {
439
- // Accept either array _fields_ (Python style) or object map
440
- const fields = this._fields_ || {};
441
- let mapFields = {};
471
+ // Definizione della classe stessa: una sottoclasse non eredita quella
472
+ // della base (ha un layout proprio, vedi _buildStruct).
473
+ static get _structDef() {
474
+ const own = this[kStructDef];
475
+ return own !== undefined && own.owner === this ? own.def : undefined;
476
+ }
442
477
 
478
+ static set _structDef(def) {
479
+ // null/undefined invalida la cache (il layout viene ricostruito).
480
+ if (def === null || def === undefined) {
481
+ delete this[kStructDef];
482
+ return;
483
+ }
484
+ // { owner, def }: una sottoclasse eredita la proprietà ma non è `owner`.
485
+ Object.defineProperty(this, kStructDef, { value: { owner: this, def }, configurable: true, writable: true });
486
+ installFieldAccessors(this, def);
487
+ }
488
+
489
+ // Classe base con un layout (Python: la sottoclasse ne estende i campi),
490
+ // null per le basi della libreria (Structure, Union, BigEndianStructure...).
491
+ static _baseLayoutClass() {
492
+ const parent = Object.getPrototypeOf(this);
493
+ for (let c = parent; typeof c === "function" && c.prototype instanceof Structure; c = Object.getPrototypeOf(c)) {
494
+ if (Object.hasOwn(c, "_fields_") || c._structDef !== undefined) return parent;
495
+ }
496
+ return null;
497
+ }
498
+
499
+ // `_fields_` della classe come coppie [name, type] nell'ordine dichiarato
500
+ // (un oggetto metterebbe prima i nomi come "1"), con i bitfield
501
+ // `[name, type, bits]` e (se `withAnonymous`) i campi di `_anonymous_`
502
+ // come { anonymous: true, type, cls }.
503
+ static _fieldMap(withAnonymous = true) {
504
+ const fields = Object.hasOwn(this, "_fields_") ? this._fields_ : {};
505
+ let entries;
443
506
  if (Array.isArray(fields)) {
444
- for (const entry of fields) {
445
- if (Array.isArray(entry) && entry.length >= 2) {
446
- const name = entry[0];
447
- const type = entry[1];
448
- // Python-style bitfield: [name, type, bits]
449
- if (entry.length >= 3 && typeof entry[2] === "number") {
450
- mapFields[name] = bitfield(type, entry[2]);
451
- } else {
452
- mapFields[name] = type;
453
- }
507
+ entries = fields.map((entry) => {
508
+ const valid = Array.isArray(entry) && typeof entry[0] === "string" && entry[1] != null && (entry.length === 2 || (entry.length === 3 && typeof entry[2] === "number"));
509
+ if (!valid) {
510
+ throw new TypeError("_fields_ must be a sequence of (name, C type) pairs or (name, C type, bit size) triples");
454
511
  }
455
- }
512
+ return entry.length === 3 ? [entry[0], bitfield(entry[1], entry[2])] : [entry[0], entry[1]];
513
+ });
456
514
  } else if (typeof fields === "object" && fields !== null) {
457
- mapFields = { ...fields };
515
+ entries = Object.entries(fields);
516
+ } else {
517
+ entries = [];
458
518
  }
459
519
 
460
- // Handle anonymous fields list: convert to { anonymous: true, type: T }
461
- if (Array.isArray(this._anonymous_)) {
462
- for (const anonName of this._anonymous_) {
463
- if (mapFields[anonName] !== undefined) {
464
- let anonType = mapFields[anonName];
465
- // Normalize type: if it's a Structure/Union class, get its _structDef
466
- if (typeof anonType === "function" && typeof anonType._buildStruct === "function") {
467
- anonType = anonType._structDef || anonType._buildStruct();
468
- }
469
- mapFields[anonName] = {
470
- anonymous: true,
471
- type: anonType,
472
- };
520
+ if (withAnonymous && Array.isArray(this._anonymous_)) {
521
+ const anonymous = new Set(this._anonymous_);
522
+ entries = entries.map(([name, type]) => {
523
+ if (!anonymous.has(name)) return [name, type];
524
+ // Classe Structure/Union: la sua definizione, e la classe per le istanze.
525
+ if (typeof type === "function" && typeof type._buildStruct === "function") {
526
+ return [name, { anonymous: true, type: type._structDef || type._buildStruct(), cls: type }];
473
527
  }
474
- }
528
+ return [name, { anonymous: true, type }];
529
+ });
475
530
  }
531
+ return entries;
532
+ }
476
533
 
534
+ // Opzioni di layout della classe (ereditate, come getattr in Python):
535
+ // `_pack_`, `_layout_`, `_align_` e byte order.
536
+ static _layoutOptions() {
477
537
  const options = {};
478
538
  if (this._pack_ !== undefined) {
479
539
  // Python ctypes: `_pack_` is a positive integer specifying the maximum
@@ -492,14 +552,34 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
492
552
  }
493
553
  if (options.pack !== undefined) options.packed = true;
494
554
  }
555
+ // Python ctypes: "ms" (Windows, or with _pack_) or "gcc-sysv" bitfield layout.
556
+ if (this._layout_ !== undefined) options.layout = this._layout_;
557
+ // Python ctypes: `_align_` raises the minimum alignment of the type.
558
+ if (this._align_ !== undefined) options.align = this._align_;
495
559
  // Python ctypes: `_swappedbytes_` (or the BigEndianStructure /
496
560
  // LittleEndianStructure base class) requests byte-swapped fields.
497
561
  // We only officially support LE hosts, so `swapped: true` ⇒ BE layout.
498
562
  if (this._swappedbytes_ === true || this._swapped_ === true) {
499
563
  options.swapped = true;
500
564
  }
565
+ return options;
566
+ }
501
567
 
502
- const def = struct(mapFields, options);
568
+ // Build the underlying struct definition and cache it on the constructor
569
+ static _buildStruct() {
570
+ const own = this._structDef;
571
+ if (own !== undefined) return own;
572
+ const Base = this._baseLayoutClass();
573
+ const base = Base === null ? null : Base._structDef || Base._buildStruct();
574
+ // Python: una sottoclasse senza _fields_ propri ha il layout della base.
575
+ if (base !== null && !Object.hasOwn(this, "_fields_")) {
576
+ this._structDef = base;
577
+ return base;
578
+ }
579
+ if (base !== null && base.isUnion) {
580
+ throw new TypeError("a Structure cannot extend a Union");
581
+ }
582
+ const def = struct(this._fieldMap(), { ...this._layoutOptions(), base });
503
583
  this._structDef = def;
504
584
  return def;
505
585
  }
@@ -559,7 +639,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
559
639
 
560
640
  // Bulk operations for better performance
561
641
  setFields(fields) {
562
- for (const [name, value] of Object.entries(fields)) {
642
+ for (const [name, value] of Object.entries(fieldsOf(fields))) {
563
643
  this.__structDef.set(this.__buffer, name, value);
564
644
  }
565
645
  }
@@ -572,7 +652,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
572
652
  return result;
573
653
  }
574
654
 
575
- // bulk operations (Proxy reads directly from buffer - no cache needed)
655
+ // bulk operations (fields read directly from the buffer - no cache needed)
576
656
  withBulkUpdate(callback) {
577
657
  return callback(this);
578
658
  }
@@ -82,29 +82,18 @@ export function createUnionClass(Structure, union, bitfield) {
82
82
  */
83
83
  class Union extends Structure {
84
84
  static _buildStruct() {
85
- const fields = this._fields_ || {};
86
- let mapFields = {};
87
- if (Array.isArray(fields)) {
88
- for (const entry of fields) {
89
- if (Array.isArray(entry) && entry.length >= 2) {
90
- const name = entry[0];
91
- const type = entry[1];
92
- // Python-style bitfield: [name, type, bits]
93
- if (entry.length >= 3 && typeof entry[2] === "number") {
94
- mapFields[name] = bitfield(type, entry[2]);
95
- } else {
96
- mapFields[name] = type;
97
- }
98
- }
99
- }
100
- } else if (typeof fields === "object" && fields !== null) {
101
- mapFields = fields;
85
+ if (this._structDef !== undefined) return this._structDef;
86
+ const Base = this._baseLayoutClass();
87
+ const base = Base === null ? null : Base._structDef || Base._buildStruct();
88
+ // Python: una sottoclasse senza _fields_ propri ha il layout della base.
89
+ if (base !== null && !Object.hasOwn(this, "_fields_")) {
90
+ this._structDef = base;
91
+ return base;
102
92
  }
103
- const options = {};
104
- if (this._swappedbytes_ === true || this._swapped_ === true) {
105
- options.swapped = true;
93
+ if (base !== null && !base.isUnion) {
94
+ throw new TypeError("a Union cannot extend a Structure");
106
95
  }
107
- const def = union(mapFields, options);
96
+ const def = union(this._fieldMap(), { ...this._layoutOptions(), base });
108
97
  this._structDef = def;
109
98
  return def;
110
99
  }