How does inheritance and vtables work wrt. C++ and interop with D? Fns w/ Multiple-inheritance args impossible to bind to?

Gavin Ray gavinray at site.com
Tue May 25 17:52:14 UTC 2021


On Tuesday, 25 May 2021 at 06:02:55 UTC, evilrat wrote:
> Anyway all this stuff requires thorough research & testing as 
> such ABI tinkering is very easy to mess up and very hard to 
> debug, for example if you mess up the order(functions layout) 
> it can land on another final method call that seemingly work 
> but in debugger you'll see that you can't hit breakpoint in 
> that method.
> Happy debugging time!

Ahh, that works!

It also works without the `cast(BaseType)` if you use `alias` in 
the class:
```d
import core.stdc.stdio : printf;
extern (C++)
{
   void takesADerived(Derived derived);
   Derived createTestDerivedCPP();

   extern interface Base1
   {
     void overrideMe1();

     pragma(mangle, "?getSomething at Base1@@QEAA?BHXZ")
     final int getSomething();

     pragma(mangle, "?inheritedFunctionWithArgs at Base1@@QEAAHHH at Z")
     final int inheritedFunctionWithArgs(int x, int y);
   }

   extern interface Base2
   {
     void overrideMe2();

     pragma(mangle "?getOtherThing at Base2@@QEAA?BHXZ")
     final int getOtherThing();
   }

   extern class Derived : Base1, Base2
   {
     int someInt;

     alias getSomething = Base1.getSomething;
     alias inheritedFunctionWithArgs = 
Base1.inheritedFunctionWithArgs;

     this(int someIntVal) { this.someInt = someIntVal; }

     void overrideMe1() { printf("[D] Dlang Derived overrideMe1 
called \n"); }
     void overrideMe2() { printf("[D] Dlang Derived overrideMe1 
called \n"); }
   }
}

void main()
{
   Derived dlangDerived = new Derived(123);
   printf("[D] Derived.Base1::getSomething() = %d \n", 
dlangDerived.getSomething());
   printf("[D] Derived.Base2::getOtherThing() = %d \n", 
dlangDerived.getOtherThing());
   printf("[D] Derived.Base1::inheritedFunctionWithArgs(5, 10) = 
%d \n",
       dlangDerived.inheritedFunctionWithArgs(5, 10));
   printf("[D] Calling C++ takesADerived() with D Derived* \n");
   takesADerived(dlangDerived);
}
```

![output](https://i.imgur.com/Plbtlow.png)

Just you wait, I'll learn enough to be of any use contributing to 
OMG yet! haha


More information about the Digitalmars-d-learn mailing list