shared-libraries - d2 : Calling writefln in D shared libraries from C side

标签 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,它就会因段错误而失败.我究竟做错了什么?

我调用 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/

相关文章:

d - 为什么 readf 不返回值?

linux - 为 ARM 交叉编译时共享对象导入错误

c - 需要一个允许我从内存地址加载共享对象的 API

c++ - 在 solaris 上创建和使用动态共享库

string - 将 http 响应压缩为字符串的精确副本

class - 访问外部类

c# - D 的作用域失败/成功/退出是否必要?

Json + D - 如何设置 JSONValue 的节点类型?

c++ - 如何使用 Clang 更喜欢一个图书馆位置而不是另一个图书馆位置?

linux - 使用 glibc 而不是默认库 : Permission denied on execution 编译的 C 程序