自从我开始尝试从 C++ 调用一些 D 代码(使用为 C++ 和 D 定义的类/接口(interface))。
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。
最佳答案
返回指向 GC 堆的 C++ 指针是个坏主意 - 请改用 malloc
/emplace
(或 std.experimental.allocator.make)并在 C++ 端调用
free。不过,这不会运行析构函数,因此您可能还想公开一个调用
destroy` 的 D 函数。
顺便说一句,无需返回 void*
并强制转换 - 只需从 createBufferCppBinding
返回 BufferCppBindingInterface
。
关于C++ 到 D 的互操作性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33504210/