C ++到D的互操作性

时间:2015-11-03 16:26:31

标签: 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;
    }
}

usage(C ++):

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

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

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

我刚收到SIGSEGV。

1 个答案:

答案 0 :(得分:2)

返回指向GC堆的C ++指针是一个坏主意 - 使用malloc / emplace(或std.experimental.allocator.make) instead and call免费on the C++ side. That won't run destructors though, so maybe you want to expose a D function that calls destroy`。

BTW,无需返回void*并退回 - 只需从BufferCppBindingInterface返回createBufferCppBinding