Search code examples
c++d

implement class in D and instanciate / lifetimetrack in C++


I try to implement a class in D and export it to C++. In difference to the example in this tutorial I want to control the lifetime in C++. I thought it would be possible to call a factory method in D, create a instance, mark it as gcRoot and return it. When C++ does no longer need this class it would call a function in D to unmark the instance as GCRoot. The following code compiles but results in a sigsegv when calling the count function from c++

D-Code:

import core.memory;

extern (C++) interface B {
public:
    extern (C++) int count();

private:
}

class D : B {
    extern (C++)int count() { return 10; }
};

extern (C++) B*   CreateB() {
    B inst = new D();
    B* instPtr = &inst;
    core.memory.GC.addRoot(instPtr);

    return instPtr;
}

C++Code:

class B {
public:
   virtual int count();
};

B* CreateB();

extern "C" int rt_init();

int main(int argc, char *argv[])
{
    rt_init();

    B* b = CreateB();
    int i = b->count();
    return 0;
}

Solution

  • Your problem is that in D class is already reference type (pointer) so you can not dereference it again:

    import core.memory;
    
    extern (C++) interface B {
    public:
        extern (C++) int count();
    
    private:
    }
    
    class D : B {
        extern (C++)int count() { return 10; }
    }
    
    extern (C++) B CreateB() {
        B inst = new D();
        core.memory.GC.addRoot(cast(void *)inst);
        return inst;
    }