我正在尝试使用 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);
}
它构建良好,并且工作正常。但是当我尝试使用以下更多 D'ish 来源时:
module testlib;
import std.stdio;
extern (C) export int hello(int a) {
writefln("Number is %d", a);
return (a + 1);
}
一旦我尝试调用
hello
,它就会因段错误而失败.我究竟做错了什么?我调用
hello
使用 Python:import ctypes
testlib = ctypes.CDLL('testlib.dylib');
print (testlib.hello(10))
UPD1:似乎我也不能使用像
std.conv.to!(string)
这样的 Phobos 功能.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();
}
可能,Linux 和 Mac OS X 中有一些方法可以自动调用这些函数,但我对此感到满意。
关于shared-libraries - d2 : Calling writefln in D shared libraries from C side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758255/