node-ctypes 2.1.1 → 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.
- package/README.md +98 -13
- package/build/Release/ctypes-darwin-arm64.node +0 -0
- package/build/Release/ctypes-darwin-x64.node +0 -0
- package/build/Release/ctypes-linux-arm64-musl.node +0 -0
- package/build/Release/ctypes-linux-arm64.node +0 -0
- package/build/Release/ctypes-linux-x64-musl.node +0 -0
- package/build/Release/ctypes-linux-x64.node +0 -0
- package/build/Release/ctypes-win32-arm64.node +0 -0
- package/build/Release/ctypes-win32-x64.node +0 -0
- package/lib/core/Library.js +86 -76
- package/lib/core/callback.js +10 -17
- package/lib/core/conversions.js +193 -3
- package/lib/core/funcptr.js +67 -52
- package/lib/core/lazy-loader.js +10 -4
- package/lib/core/types.js +196 -98
- package/lib/index.d.ts +193 -47
- package/lib/index.js +51 -28
- package/lib/memory/buffer.js +66 -19
- package/lib/memory/mirror.js +283 -0
- package/lib/memory/operations.js +59 -42
- package/lib/memory/pointer.js +180 -61
- package/lib/platform/constants.js +0 -1
- package/lib/platform/errors.js +48 -4
- package/lib/platform/find_library.js +78 -19
- package/lib/structures/Structure.js +260 -172
- package/lib/structures/Union.js +10 -21
- package/lib/structures/helpers/array.js +235 -92
- package/lib/structures/helpers/bitfield.js +66 -150
- package/lib/structures/helpers/common.js +115 -15
- package/lib/structures/helpers/layout.js +131 -0
- package/lib/structures/helpers/struct.js +144 -400
- package/lib/structures/helpers/union.js +132 -142
- package/lib/structures/helpers/wrap.js +29 -17
- package/lib/types/SimpleCData.js +14 -7
- package/lib/types/primitives.js +130 -101
- package/package.json +2 -1
|
@@ -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
|
-
*
|
|
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.
|
|
@@ -64,6 +64,9 @@
|
|
|
64
64
|
* ```
|
|
65
65
|
*/
|
|
66
66
|
|
|
67
|
+
import { kMirrorBase, mirrorBase, mirroredAccessors, mirrorsActive } from "../memory/mirror.js";
|
|
68
|
+
import { fieldsOf } from "./helpers/common.js";
|
|
69
|
+
|
|
67
70
|
/**
|
|
68
71
|
* Creates the Structure base class with required dependencies injected.
|
|
69
72
|
*
|
|
@@ -73,125 +76,135 @@
|
|
|
73
76
|
* @returns {Class} Structure base class
|
|
74
77
|
* @private
|
|
75
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
|
+
|
|
76
96
|
export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
77
97
|
// Buffer dell'istanza, letto dall'handler condiviso. Chiave privata e non
|
|
78
98
|
// `__buffer`, così riassegnare `__buffer` non cambia i campi (come prima).
|
|
79
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
|
+
}
|
|
80
123
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
+
}
|
|
88
131
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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 = [];
|
|
93
142
|
for (const field of def.fields) {
|
|
94
|
-
|
|
143
|
+
names.push(field.name);
|
|
95
144
|
if (field.isAnonymous && field.type && Array.isArray(field.type.fields)) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
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);
|
|
99
148
|
}
|
|
100
149
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
get(
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if (prop === Symbol.toStringTag) return target.constructor.name || "Structure";
|
|
121
|
-
return undefined;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
if (prop === "_buffer" || prop === "__buffer") return target[kBuffer];
|
|
125
|
-
if (prop === "_structDef" || prop === "__structDef") return def;
|
|
126
|
-
// La classe, non una sua copia legata (x.constructor === Point).
|
|
127
|
-
if (prop === "constructor") return target.constructor;
|
|
128
|
-
|
|
129
|
-
const method = target[prop];
|
|
130
|
-
if (typeof method === "function") {
|
|
131
|
-
// Bind al Proxy (receiver), NON al target raw. Un metodo custom
|
|
132
|
-
// come `mag2() { return this.x * this.x + ... }` dentro fa
|
|
133
|
-
// `this.x` che deve passare attraverso il Proxy get trap per
|
|
134
|
-
// leggere il field. Binding su `target` (istanza raw) salta
|
|
135
|
-
// il trap e ritorna undefined → NaN nei calcoli.
|
|
136
|
-
return method.bind(receiver);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return Reflect.get(target, prop, receiver);
|
|
140
|
-
},
|
|
141
|
-
set(target, prop, value, receiver) {
|
|
142
|
-
// FAST PATH: pre-compiled writer (null-proto obj, bracket access)
|
|
143
|
-
if (typeof prop === "string") {
|
|
144
|
-
const writer = writers !== undefined ? writers[prop] : undefined;
|
|
145
|
-
if (writer !== undefined) {
|
|
146
|
-
writer(target[kBuffer], value);
|
|
147
|
-
return true;
|
|
148
|
-
}
|
|
149
|
-
if (allFieldNames[prop] === true) {
|
|
150
|
-
def.set(target[kBuffer], prop, value);
|
|
151
|
-
return true;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
return Reflect.set(target, prop, value, receiver);
|
|
156
|
-
},
|
|
157
|
-
has(target, prop) {
|
|
158
|
-
if (typeof prop === "string" && allFieldNames[prop] === true) return true;
|
|
159
|
-
if (prop === "_buffer" || prop === "_structDef" || prop === "toObject") return true;
|
|
160
|
-
return Reflect.has(target, prop);
|
|
161
|
-
},
|
|
162
|
-
ownKeys(target) {
|
|
163
|
-
const keys = [];
|
|
164
|
-
for (const f of def.fields) {
|
|
165
|
-
if (f.isAnonymous && f.type && Array.isArray(f.type.fields)) {
|
|
166
|
-
for (const sf of f.type.fields) {
|
|
167
|
-
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);
|
|
168
169
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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);
|
|
195
208
|
}
|
|
196
209
|
|
|
197
210
|
// Scrittore precompilato del campo quando esiste, altrimenti def.set generico.
|
|
@@ -219,12 +232,12 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
219
232
|
* Structure base class for creating C-style structures.
|
|
220
233
|
*
|
|
221
234
|
* Users extend this class and define static `_fields_` to specify the struct layout.
|
|
222
|
-
* The constructor handles memory allocation
|
|
223
|
-
*
|
|
235
|
+
* The constructor handles memory allocation and field initialization; the
|
|
236
|
+
* fields are accessors of the class prototype (Python: field descriptors).
|
|
224
237
|
*
|
|
225
238
|
* **Key Features**:
|
|
226
239
|
* - Automatic memory layout based on `_fields_`
|
|
227
|
-
* -
|
|
240
|
+
* - Field accessors shared by all instances of the class
|
|
228
241
|
* - Support for positional arguments in constructor
|
|
229
242
|
* - Buffer wrapping for zero-copy operations
|
|
230
243
|
* - Anonymous field support via `_anonymous_`
|
|
@@ -280,14 +293,19 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
280
293
|
class Structure {
|
|
281
294
|
constructor(...args) {
|
|
282
295
|
const Ctor = this.constructor;
|
|
283
|
-
|
|
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();
|
|
284
300
|
let buf;
|
|
285
301
|
|
|
286
302
|
// Support positional args: new Point(10,20)
|
|
287
303
|
// Un'istanza di struct/union come unico argomento è posizionale
|
|
288
304
|
// (Python: RECT(point)), non un oggetto di inizializzazione per nome.
|
|
289
305
|
const single = args.length === 1 ? args[0] : undefined;
|
|
290
|
-
|
|
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);
|
|
291
309
|
if (isNamedInit) {
|
|
292
310
|
// alloc() restituisce un buffer già azzerato (Buffer.alloc)
|
|
293
311
|
buf = alloc(def.size);
|
|
@@ -307,18 +325,54 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
307
325
|
if (args.length > 0) {
|
|
308
326
|
// Positional mapping to non-anonymous declared fields order
|
|
309
327
|
const ordered = getPositionalFields(def);
|
|
310
|
-
|
|
328
|
+
if (args.length > ordered.length) throw new TypeError("too many initializers");
|
|
329
|
+
for (let i = 0; i < args.length; i++) {
|
|
311
330
|
setField(def, buf, ordered[i].name, args[i]);
|
|
312
331
|
}
|
|
313
332
|
}
|
|
314
333
|
}
|
|
315
334
|
|
|
316
|
-
// Store internal references on this (needed for methods like toObject)
|
|
317
|
-
this.__buffer = buf;
|
|
318
|
-
this.__structDef = def;
|
|
319
335
|
this[kBuffer] = buf;
|
|
336
|
+
this[kDef] = def;
|
|
337
|
+
this[kViews] = undefined;
|
|
338
|
+
// Indirizzo di una copia di memoria nativa (Electron), undefined altrimenti.
|
|
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
|
+
}
|
|
320
351
|
|
|
321
|
-
|
|
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)}`;
|
|
322
376
|
}
|
|
323
377
|
|
|
324
378
|
// Static getters for size, alignment, and fields (enables use as nested type)
|
|
@@ -353,14 +407,10 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
353
407
|
* @returns {Structure} A new instance sharing memory with source.
|
|
354
408
|
*/
|
|
355
409
|
static from_buffer(source, offset = 0) {
|
|
356
|
-
if (!Buffer.isBuffer(source)) {
|
|
357
|
-
throw new TypeError("from_buffer: source must be a Buffer");
|
|
358
|
-
}
|
|
359
410
|
const def = this._structDef || this._buildStruct();
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
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));
|
|
364
414
|
}
|
|
365
415
|
|
|
366
416
|
/**
|
|
@@ -371,22 +421,13 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
371
421
|
*
|
|
372
422
|
* @param {Buffer|Uint8Array} source - Bytes to copy from.
|
|
373
423
|
* @param {number} [offset=0] - Byte offset into source.
|
|
374
|
-
* @returns {Structure} A new instance with
|
|
424
|
+
* @returns {Structure} A new instance with its own buffer.
|
|
375
425
|
*/
|
|
376
426
|
static from_buffer_copy(source, offset = 0) {
|
|
377
|
-
if (!Buffer.isBuffer(source) && !(source instanceof Uint8Array)) {
|
|
378
|
-
throw new TypeError("from_buffer_copy: source must be a Buffer or Uint8Array");
|
|
379
|
-
}
|
|
380
427
|
const def = this._structDef || this._buildStruct();
|
|
381
|
-
|
|
382
|
-
throw new RangeError(`from_buffer_copy: source too small (${source.length - offset} < ${def.size})`);
|
|
383
|
-
}
|
|
428
|
+
const bytes = sourceBytes(source, offset, def.size, "from_buffer_copy");
|
|
384
429
|
const copy = Buffer.alloc(def.size);
|
|
385
|
-
|
|
386
|
-
source.copy(copy, 0, offset, offset + def.size);
|
|
387
|
-
} else {
|
|
388
|
-
copy.set(source.subarray(offset, offset + def.size));
|
|
389
|
-
}
|
|
430
|
+
copy.set(bytes.subarray(offset, offset + def.size));
|
|
390
431
|
return new this(copy);
|
|
391
432
|
}
|
|
392
433
|
|
|
@@ -402,7 +443,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
402
443
|
*/
|
|
403
444
|
static from_address(address) {
|
|
404
445
|
if (!ptrToBuffer) {
|
|
405
|
-
throw new Error("from_address requires the native module (
|
|
446
|
+
throw new Error("from_address requires the native module (not loaded)");
|
|
406
447
|
}
|
|
407
448
|
const addr = typeof address === "bigint" ? address : BigInt(address);
|
|
408
449
|
const def = this._structDef || this._buildStruct();
|
|
@@ -427,45 +468,72 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
427
468
|
}
|
|
428
469
|
|
|
429
470
|
// Build the underlying struct definition and cache it on the constructor
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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
|
+
}
|
|
434
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;
|
|
435
506
|
if (Array.isArray(fields)) {
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
// Python-style bitfield: [name, type, bits]
|
|
441
|
-
if (entry.length >= 3 && typeof entry[2] === "number") {
|
|
442
|
-
mapFields[name] = bitfield(type, entry[2]);
|
|
443
|
-
} else {
|
|
444
|
-
mapFields[name] = type;
|
|
445
|
-
}
|
|
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");
|
|
446
511
|
}
|
|
447
|
-
|
|
512
|
+
return entry.length === 3 ? [entry[0], bitfield(entry[1], entry[2])] : [entry[0], entry[1]];
|
|
513
|
+
});
|
|
448
514
|
} else if (typeof fields === "object" && fields !== null) {
|
|
449
|
-
|
|
515
|
+
entries = Object.entries(fields);
|
|
516
|
+
} else {
|
|
517
|
+
entries = [];
|
|
450
518
|
}
|
|
451
519
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
if (
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
anonType = anonType._structDef || anonType._buildStruct();
|
|
460
|
-
}
|
|
461
|
-
mapFields[anonName] = {
|
|
462
|
-
anonymous: true,
|
|
463
|
-
type: anonType,
|
|
464
|
-
};
|
|
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 }];
|
|
465
527
|
}
|
|
466
|
-
|
|
528
|
+
return [name, { anonymous: true, type }];
|
|
529
|
+
});
|
|
467
530
|
}
|
|
531
|
+
return entries;
|
|
532
|
+
}
|
|
468
533
|
|
|
534
|
+
// Opzioni di layout della classe (ereditate, come getattr in Python):
|
|
535
|
+
// `_pack_`, `_layout_`, `_align_` e byte order.
|
|
536
|
+
static _layoutOptions() {
|
|
469
537
|
const options = {};
|
|
470
538
|
if (this._pack_ !== undefined) {
|
|
471
539
|
// Python ctypes: `_pack_` is a positive integer specifying the maximum
|
|
@@ -484,14 +552,34 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
484
552
|
}
|
|
485
553
|
if (options.pack !== undefined) options.packed = true;
|
|
486
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_;
|
|
487
559
|
// Python ctypes: `_swappedbytes_` (or the BigEndianStructure /
|
|
488
560
|
// LittleEndianStructure base class) requests byte-swapped fields.
|
|
489
561
|
// We only officially support LE hosts, so `swapped: true` ⇒ BE layout.
|
|
490
562
|
if (this._swappedbytes_ === true || this._swapped_ === true) {
|
|
491
563
|
options.swapped = true;
|
|
492
564
|
}
|
|
565
|
+
return options;
|
|
566
|
+
}
|
|
493
567
|
|
|
494
|
-
|
|
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 });
|
|
495
583
|
this._structDef = def;
|
|
496
584
|
return def;
|
|
497
585
|
}
|
|
@@ -551,7 +639,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
551
639
|
|
|
552
640
|
// Bulk operations for better performance
|
|
553
641
|
setFields(fields) {
|
|
554
|
-
for (const [name, value] of Object.entries(fields)) {
|
|
642
|
+
for (const [name, value] of Object.entries(fieldsOf(fields))) {
|
|
555
643
|
this.__structDef.set(this.__buffer, name, value);
|
|
556
644
|
}
|
|
557
645
|
}
|
|
@@ -564,7 +652,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
564
652
|
return result;
|
|
565
653
|
}
|
|
566
654
|
|
|
567
|
-
// bulk operations (
|
|
655
|
+
// bulk operations (fields read directly from the buffer - no cache needed)
|
|
568
656
|
withBulkUpdate(callback) {
|
|
569
657
|
return callback(this);
|
|
570
658
|
}
|
package/lib/structures/Union.js
CHANGED
|
@@ -82,29 +82,18 @@ export function createUnionClass(Structure, union, bitfield) {
|
|
|
82
82
|
*/
|
|
83
83
|
class Union extends Structure {
|
|
84
84
|
static _buildStruct() {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
104
|
-
|
|
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(
|
|
96
|
+
const def = union(this._fieldMap(), { ...this._layoutOptions(), base });
|
|
108
97
|
this._structDef = def;
|
|
109
98
|
return def;
|
|
110
99
|
}
|