如何从C结构体定义生成可实例化子类?TypeScript技术问询
实现TypeScript版C结构体解析类
我要编写一个类,能够接收C结构体定义,生成可像常规类一样使用的类型与类定义。目标是在TypeScript中解析并使用结构体,方案可灵活调整。
理想实现效果
interface TestFields { hello: 'a', } interface BooFields { world: Struct<TestFields>, wow: 'b' } export const TestStruct = Struct.define<TestFields>({ hello: 'a' }); export const BooStruct = Struct.define<BooFields>({ world: TestStruct, wow: 'b' }); let myVar = new BooStruct(); myVar.wow = 1; myVar.world.hello = 4;
尝试的精简版代码
export type FieldTypes = 'a' | 'b'; export type NestedFieldTypes = FieldTypes | Struct<any>; export interface FieldDefinition { type: NestedFieldTypes; name: string; offset: number; } export type StructFields<T> = { [K in keyof T]: T[K] extends Struct<infer U> ? U : FieldTypes; }; export class Struct<T extends StructFields<T>> { public static readonly TypeSizes: { [K in FieldTypes]: number } = { a: 1, b: 2 }; public static readonly FieldDefinitions: FieldDefinition[] = []; public get length(): number { return 1; } constructor() {} public static define<T extends StructFields<T>>(fields: T): typeof Struct<T> { const fieldDefinitions: FieldDefinition[] = []; let currentOffset = 0; for (const name in fields) { const fieldType = fields[name]; // if (fieldType instanceof Struct) { // currentOffset += (fieldType as Struct<any>).length; // fieldDefinitions.push({ type: new (fieldType as Struct<T>)(), name: name, offset: currentOffset }); // } else if (Array.isArray(fieldType) && fieldType.every(value => value instanceof Struct)) { // for (const nestedStruct of fieldType) { // currentOffset += nestedStruct.length; // } // } else { currentOffset += Struct.TypeSizes[fieldType as FieldTypes]; fieldDefinitions.push({ type: fieldType, name: name, offset: currentOffset }); // } } let result = Struct<T>; result.FieldDefinitions.push(...fieldDefinitions); return result; } }
遇到的问题
- 要么
define函数返回的是对象而非类 - 要么无法将
fieldDefinitions中的type定义为fieldType
补充说明
此处的“struct”指C结构体,该脚本用于Frida,例如wow可以是"uint32"类型,仅接受number类型的值。
内容的提问来源于stack exchange,提问作者dzervas
相关产品推荐
相关产品推荐

