2015-11-03 278 views
3

自從我嘗試從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++土地C++代碼:

class BufferCppBinding { 
public: 

    virtual void construct(); 
}; 

爲d的運行時的初始化i的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。

+0

如果你在C++中的聲明是D接口(BufferCppBindingInterface)的聲明? http://dlang.org/cpp_interface.html – TractorPulledPork

回答

2

返回指針和C++中指向GC堆是一個壞主意 - 用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 from createBufferCppBinding