dmd一个小示例,不带运行时

/*
dmd % -defaultlib=
*/

extern(C) int printf(const char*, ...);

interface I {
    int omg();
}

class A : I {
    int omg() { return 12; }
}

class B : A {
    override int omg() { return 34; }
}

template New(T) {
    pragma(mangle, "_D" ~ T.mangleof[1..$] ~ "6__initZ")
// llvm说应该是{ [2 x i8*]*, i8* },不管
    __gshared extern immutable ubyte[__traits(classInstanceSize, T)] initializer;

    T New(ref ubyte[__traits(classInstanceSize, T)] memory) {
        foreach(idx, ref b; memory) {
            b = initializer.ptr[idx];
        }
        //memory[] = initializer[];
        return cast(T) memory.ptr;
    }

    // T New() { }
}

extern(C) int main() {
    ubyte[__traits(classInstanceSize, A)] buffer;
    A a = New!B(buffer);
    I i = a;
    printf("hi %d\n", i.omg());
    return 0;
}

编译后22kb,

你可能感兴趣的:(笔记)