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

I am trying to implement a class in D and export it to C ++. Unlike the example in this tutorial, I want to control the lifetime in C ++. I thought it would be possible to call the factory method in D, create an instance, mark it as gcRoot, and return it. When C ++ no longer needs this class, it will call a function in D to cancel the instance as GCRoot. The following code compiles, but leads to 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;
}
+4
source share
1 answer

Your problem is that there is already a reference type (pointer) in class D, so you cannot 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;
}
+4

All Articles