C到D的互操作性

因为几天我试图从C调用一些D代码(带有为C和D定义的类/接口).

D代码

module BufferCppBinding;

extern (C++) void *createBufferCppBinding() {
    BufferCppBinding ptr = new BufferCppBinding();
    return cast(void*)ptr;
}

extern (C++) interface BufferCppBindingInterface {
    void construct();
    // ...
}

class BufferCppBinding : BufferCppBindingInterface {
    public Buffer thisPtr;

    public extern (C++) void construct() {
        // doesn't do anything
    }
}

用于将类型声明为C land的C代码:

class BufferCppBinding {
public:

    virtual void construct();
};

为了初始化D运行时,我在D中编写了一个小函数,它在D land中执行:

extern (C++) void initDRuntime() nothrow{
    try
    {
        Runtime.initialize();
        //result = myWinMain(hInstance, hPrevInstance, lpCmdLine, iCmdShow);
        //Runtime.terminate(&exceptionHandler);
    }
    catch (Throwable o)
    {
        //MessageBox(null, o.toString().toUTF16z, "Error", MB_OK | MB_ICONEXCLAMATION);
        //result = 0;
    }
}

用法(C):

BufferCppBinding *vertexBuffer = reinterpret_cast<BufferCppBinding*>(createBufferCppBinding());

// here happens the crash
vertexBuffer->construct();

我正在使用g 5.2和ldc2编译代码并将其与ldc2链接.

我刚拿到一个SIGSEGV.

最佳答案 返回指向GC堆的指针是一个坏主意 – 使用malloc / emplace(或std.experimental.allocator.make)代替并调用ffon.这不会运行析构函数,所以也许你想要公开一个调用destroy`的D函数.

顺便说一句,不需要返回void *并强制转换 – 只需从createBufferCppBinding返回BufferCppBindingInterface.

点赞