Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d2: Calling writefln in D shared libraries from C side

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.

like image 691
toriningen Avatar asked Mar 18 '12 12:03

toriningen


1 Answers

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.

like image 174
toriningen Avatar answered Oct 01 '22 03:10

toriningen