d="_1">对象工厂替代方案
一般,需要无需用
要
de class="prism language-cpp">d">extern(C) __gshared string[] rt_options = ["oncycle=ignore"]; de>
或
但是,如果正在
唉,
目前,编译器
应该
但是今天可做什么呢?
好吧,用
事实上,用
有个
但,我想
de class="prism language-cpp">d">module dule">sections.demo; d">import dule">core.internal.elf.io; d">import dule">sections.demo2; //用此注册处理器 mixin d">template Register(alias fn) { d">import dule">ldc.attributes; @section(".mytest") __gshared d">void function() registered = &fn; } //必须注册`挂名`来欺骗链接器,在此搞一个 d">void specialCtor() { d">import dule">std.stdio; writeln("hello special ctor"); } mixin Register!specialCtor; // impl来取它 alias SectionDataHandler = d">void function(scope d">const(ubyte)[] data); d">int findSectionInfo(SectionDataHandler handler) { d">import dule">core.internal.elf.dl; SharedObject exe = SharedObject.thisExecutable(); ElfFile file; d">if(!ElfFile.open(exe.name.ptr, file)) d">return 1; foreach(index, name, sectionHeader; file.namedSections) { d">if(name == ".mytest") { d">if(d">auto offset = sectionHeader.shdr.sh_addr) { d">auto beg = exe.baseAddress + offset; d">auto size = sectionHeader.shdr.sh_size; d">auto data = beg[0 .. size]; //愚蠢无用的`NOGC`限制我,仅当体为`NOGC`,可标记`NOGC` alias BypassAttribute = d">void function(scope d">const(ubyte)[]) @nogc nothrow; (cast(BypassAttribute) handler)(cast(ubyte[]) data); } d">else { // 未映射 } } } d">return 0; } d">void main() { d">import dule">std.stdio; // 从列表中调用函数 d">static d">void handler(scope d">const(ubyte)[] data) { //必须引用`神奇节`中的一个变量,否则`--gc-sectionsarg`默认链接器会去掉它! d">auto reference = registered; reference(); d">auto fns = cast(d">void function()[]) data; foreach(fn; fns) { // 不要重复调用根引用 d">if(fn is reference) d">continue; fn(); } } writeln(findSectionInfo(&handler)); } de>
还有第二个
de class="prism language-cpp">d">module dule">sections.demo2; d">import dule">sections.demo; d">void otherCtor() { d">import dule">std.stdio; writeln("here too"); } mixin Register!otherCtor; de>
注意,我用了
de class="prism language-cpp">$ ldc2 -i=core.internal.elf sections.d sections2.d && ./sections hello special ctor here too 0 de>
注意,我用
否则,只需
在此
甚至可这样注册
可用