[Issue 21690] Unable to dynamic cast extern(C++) classes
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Thu Mar 11 00:22:20 UTC 2021
https://issues.dlang.org/show_bug.cgi?id=21690
--- Comment #9 from Basile-z <b2.temp at gmx.com> ---
dynamic cast of c++ classes can work to a **very** limited extent that is if
the target type is **exactly** the same (i.e not one of its derivate). This can
be done by comparing the virtual table address of the instance with the virtual
table address of the target type.
---
extern(C++) class A { void f(){}}
extern(C++) class B : A { override void f(){} }
extern(C++) class C : A { }
extern(C++) T dyncast(T, U)(U u)
{
const void* u_vtbl = *(cast(void**) u);
const void* t_vtbl = &T.classinfo.vtbl[0];
return t_vtbl is u_vtbl ? cast(T) u : null;
}
void main(string[] args)
{
B b = new B;
A a = b;
C c = new C;
assert( dyncast!(B)(a) );
assert( !dyncast!(B)(c) );
}
---
But in now way D CastExp does that for now.
--
More information about the Digitalmars-d-bugs
mailing list