You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:53:22