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

evilrat evilrat666 at gmail.com
Tue May 25 11:38:03 UTC 2021


On Tuesday, 25 May 2021 at 08:10:25 UTC, sighoya wrote:
> On Tuesday, 25 May 2021 at 02:47:19 UTC, Gavin Ray wrote:
>
>> The below seems to work at least, which is encouraging:
>
> Awesome!
> At least, it becomes problematic with fields in base classes, 
> it would be nice if we could map them to @property annotated 
> functions in D interfaces.

I did some basic testing with code above, it seems class layout 
is recursively linear at least on Windows, and D follows C++ 
rules close enough, at least it works if one comments out all but 
the first base, and the rest can be hand crafted using structs 
and templates.


With this code it is possible to pass back C++ class received 
from C++ code and call it.
So it seems support for multiple inheritance shouldn't be that 
hard to implement (for Windows), no idea how it works on Linux 
though.
```d

// replacement for second base
template iBase2() {
     // final is needed or it will call overrideMe1 instead of this
     final void overrideMe2() {
         static struct _layout {
             void* b1;
             void* b2;
             int someInt;
         }

         _layout* base = cast(_layout*) cast(void*) this;
         alias fn = extern(C++) void function(void*);

         fn _fn = *cast(fn*) base.b2; // vtable for Base2, 
vtable[0] is overrideMe2
         _fn(cast(void*)this);
     }
}

class Derived : Base1 //, Base2 {
     mixin iBase2 __base2;
     alias overrideMe2 = __base2.overrideMe2;


     static assert(Derived.someInt.offsetof == 16); // that's 
important otherwise D ctor will mess up everything
}
```

Maybe I'll be able to create templated base class that does all 
this stuff with mixins and templates.

like this
```d
extern(C++)
abstract class MultipleInheritance(T...)
{
   // implementation //
}

class Derived : MultipleInheritance!(Base1, Base2)
{ ... }
```


More information about the Digitalmars-d-learn mailing list