Should this always work?

Mike Parker aldacron at gmail.com
Sat May 1 06:17:36 UTC 2021


On Saturday, 1 May 2021 at 04:55:10 UTC, frame wrote:
> I always thought as long as an object implements an interface, 
> it should be able to cast it from a void* if it really points 
> to a supporting object.

No. An interface is like a pointer to a pointer. So to get to the 
class, you have to go one more level of indirection.

```d
import std.stdio;

interface I {
     void doIt();
}

class A : I {
     void doIt() { writeln("Doing it"); }
}

void main()
{
     I i = new A;
     void** pi = cast(void**)i;
     A a = cast(A)(*pi);
     a.doIt();
}
```

>
> If the runtime could not successfully cast it to AI, it should 
> return null. Am I wrong here?

That only works when you're casting one class/interface reference 
to another. It doesn't work when you're casting raw pointers.


More information about the Digitalmars-d-learn mailing list