C++ 到 D 的互操作性

标签 c++ d

自从我开始尝试从 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/

相关文章:

c++ - 在函数内声明 const 而不是变量有什么好处吗?

vector 和字符串的 C++ 段错误

http - 为获取的文件设置 MIME 类型

memory - 关闭 D 垃圾收集器

compiler-errors - 错误: module `string` is in file 'std/c/string.d' which cannot be read

c# - 基于ANTLR v3的成熟编译器

c++ - 动态数组...复制构造函数、析构函数、重载赋值运算符

c++ - 在 For 循环 C++ 中创建线程

c++ - 返回临时人员的复制省略

user-interface - 使用 Winelib 移植仅限 Windows 的 GUI 工具包