d2:从C端调用D共享库中的writefln

时间:2012-03-18 12:24:04

标签: shared-libraries d

我正在尝试使用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,它就会失败并出现分段错误。我做错了什么?

我正在使用Python调用hello

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()仍然失败并出现分段错误。

1 个答案:

答案 0 :(得分:5)

解决方案很简单,但很棒:

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中有一些方法可以自动调用这些函数,但我对此感到满意。