I'm trying to quickstart with dynamic shared libraries in D, but I'm having a problem.
I'm building following code with 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);
}
It builds fine, and works. But when I'm trying to make use of following more D'ish source:
module testlib;
import std.stdio;
extern (C) export int hello(int a) {
writefln("Number is %d", a);
return (a + 1);
}
It fails with segmentation fault once I'm trying to call hello
. What am I doing wrong?
I'm calling hello
using Python:
import ctypes
testlib = ctypes.CDLL('testlib.dylib');
print (testlib.hello(10))
UPD1: Seems that I also cannot use Phobos functions like std.conv.to!(string)
.
UPD2: There is no such problem on Windows, everything seems to work fine. Mac OS X suffers from this.
UPD3: Possibly, this is connected with GC. I must somehow initialize GC, but core.memory.GC.enable() still fails with segmentation fault.
Solution is simple, yet brilliant:
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();
}
Possibly, there are ways in Linux and Mac OS X to call these functions automagically, but I'm satisfied with even this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With