tor*_*gen 6 d shared-libraries
我正在尝试使用D中的动态共享库快速启动,但我遇到了问题.
我正在构建以下代码dmd -shared ./testlib.d:
module testlib;
import std.c.stdio;
extern (C) export int hello(int a) {
printf("Number is %d", a);
return (a + 1);
}
Run Code Online (Sandbox Code Playgroud)
它构建良好,并且有效.但是,当我试图利用以下更多的D'ish来源时:
module testlib;
import std.stdio;
extern (C) export int hello(int a) {
writefln("Number is %d", a);
return (a + 1);
}
Run Code Online (Sandbox Code Playgroud)
一旦我试图打电话,它就会失败并出现分段错误hello.我究竟做错了什么?
我正在hello使用Python 调用:
import ctypes
testlib = ctypes.CDLL('testlib.dylib');
print (testlib.hello(10))
Run Code Online (Sandbox Code Playgroud)
UPD1:似乎我也不能使用像Phobos这样的功能std.conv.to!(string).
UPD2: Windows上没有这样的问题,一切似乎都运行正常.Mac OS X受此影响.
UPD3:可能与GC连接.我必须以某种方式初始化GC,但core.memory.GC.enable()仍然失败并出现分段错误.
解决方案简单而又精彩:
static import core.runtime;
extern (C) export void init() { // to be called once after loading shared lib
core.runtime.Runtime.initialize();
}
extern (C) export void done() { // to be called before unloading shared lib
core.runtime.Runtime.terminate();
}
Run Code Online (Sandbox Code Playgroud)
可能在Linux和Mac OS X中有一些方法可以自动调用这些函数,但我对此感到满意.