Safely Casting An AActor* to IMyInterface* ?

I have the following interface declarations and some function that tries to cast an actor to my interface. Is this an acceptable way to cast to an interface with the Unreal framework?

UINTERFACE(MinimalAPI)
class UMyInterface: public UInterface
{
	GENERATED_BODY()
};

class MYSTUFF_API IMyInterface
{
	GENERATED_BODY()
public:
}


void USomeClass::someFunction()
{
        AActor* actor = somehowGetActor();
        if( actor->GetClass()->ImplementsInterface(UMyInterface::StaticCalss()) )
        {
                void* castAddress = actor->GetInterfaceAddress(UMyInterface::StaticClass());
                IMyInterface* interface = Cast<IMyInterface>( castAddress );
        }
}

Good news! It’s much easier than that. You just have to try casting your object to the interface class. If the cast succeeds, that object implements the interface, and you can call your interface functions as desired. If the cast fails, the object does not implement the interface.

So your code might look something like:

void USomeClass::SomeFunction()
{
    AActor* actor = SomehowGetActor();
    IMyInterface* TheInterface = Cast<IMyInterface>(actor);
    if(TheInterface)
    {
        TheInterface->Execute_SomeInterfaceFunction();
    }
}

If you’re not familiar with it, check out this wiki page about Interfaces in C++, which explains and shows how to properly use them. Note that the correct way to call interface functions is to use the Execute_ prefix (this is explained further in the wiki page).

Thanks. I will give that a shot. I originally thought I could just cast to IMyInterface like this, but I was not sure. I did not realize that I needed the Execute_ prefix though. Give me some time to test this out and if all goes well I will accept this answer.

You are correct, except it appears for this one case which is the case that I am in right now: C++ Interface Cast returns NULL when implemented with Editor - UI - Unreal Engine Forums

I haven’t tested their “solution” since it appears that one person commented the workaround would not work.