6

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.

1 Answer 1

5

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.

3
  • 1
    Maybe, use RAII instead? so, create new class DRuntime and add your init function to constructor, done - to destructor. So, client just create object of this class - and it makes all job for us.
    – Raxillan
    Commented Mar 18, 2012 at 16:06
  • But what should I do if client is not written in D? E.g. how can C core instantiate DRuntime descendant?
    – toriningen
    Commented Mar 18, 2012 at 16:56
  • If you need explicitly C, what haven't C++ class, new, constructors/destructors support - just use your init/done functions in usual C-style. And you can look at dlang.org/cpp_interface.html, if not yet.
    – Raxillan
    Commented Mar 18, 2012 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.