简体   繁体   English

C ++到D的互操作性

[英]C++ to D interoperability

Since days im trying to call some D code from C++ (with an class/interface defined for C++ and D). 因为我试图从C ++调用一些D代码(带有为C ++和D定义的类/接口)。

the D code 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
    }
}

the C++ code for declaring the type to C++ land: 用于将类型声明为C ++域的C ++代码:

class BufferCppBinding {
public:

    virtual void construct();
};

for the initialisation of the D runtime i wrote a small function in D which does in D land: 为了初始化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++): usage(C ++):

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

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

I am compiling the code with g++ 5.2 and ldc2 and linking it with ldc2. 我正在使用g ++ 5.2和ldc2编译代码并将其与ldc2链接。

I just get a SIGSEGV. 我刚拿到一个SIGSEGV。

Returning pointers to C++ that point to the GC heap is a bad idea - use malloc / emplace (or std.experimental.allocator.make) instead and call free on the C++ side. That won't run destructors though, so maybe you want to expose a D function that calls 返回指向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 on the C++ side. That won't run destructors though, so maybe you want to expose a D function that calls destroy` as well. on the C++ side. That won't run destructors though, so maybe you want to expose a D function that calls destroy` on the C++ side. That won't run destructors though, so maybe you want to expose a D function that calls

BTW, no need to return void* and cast back - just return BufferCppBindingInterface from createBufferCppBinding . 顺便说一句,不需要返回void*BufferCppBindingInterface createBufferCppBinding - 只需从createBufferCppBinding返回createBufferCppBinding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM