C++ 到 D 的互操作性

4

我尝试从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++语言的C++代码:

class BufferCppBinding {
public:

    virtual void construct();
};

为了初始化D运行时,我在D语言中编写了一个小的函数,它在D语言环境中实现了以下功能:

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错误。


你的C++声明应该是D接口(BufferCppBindingInterface)吗? http://dlang.org/cpp_interface.html - TractorPulledPork
1个回答

2
将指向GC堆的指针返回给C++是个坏主意 - 使用malloc/emplace(或std.experimental.allocator.make)代替,并在C++端调用free。但这样不会运行析构函数,所以也许您想公开一个D函数来调用destroy
顺便说一句,不需要返回void*并进行强制转换 - 只需从createBufferCppBinding返回BufferCppBindingInterface即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接