reinterpret_cast into UE interfaces result in access violation error

Compiler cannot jump from AActor to IMyInterface, you need to cast to AMyActor inbetween.

Internally, UE is a bit more complex than that. The cast implementation from object to interface uses the reflection system to look up object’s implemented interfaces (stored in the UClass). It accesses the UClass via GetClass() which is polymorphic, so even with your variable of type AActor* it returns the UClass of AMyActor. The UClass contains information about your interface, including its virtual table offset within AMyActor class. Then it can jump to that offset with a c-style cast.

Note the term “Script interface” can be misleading, it designates blueprint-only interfaces.

As long as you stick to C++ interfaces, you should get the same result with the following code :

AActor* Actor = GetMyActorFromSomeWhere();
AMyActor* MyActor = Cast<AMyActor>(Actor);
IMyInterface* Interface = (IMyInterface*)MyActor;
Interface->DoSomething();

Do note that the last cast is useless, as you can call directly MyActor->DoSomething().

And final note, avoid reinterpret_cast in this situation, as it prevents pointer adjustment which may be needed. A c-style cast or static_cast is better suited for upcasting.
See c++ - Does reinterpret_cast guarantee not to change the source pointer's address? - Stack Overflow

2 Likes