C++ Callback

Hey guys, Im wondering, is there an easy way to pass method as callback to another method in C++?
Mostly, Im interested in the way like it could be done in C# with Action delegates, like:

void main()
{
     MethodWithCallback(CallbackMethod);
}

public void MethodWithCallback(Action callback)
{
    //When all is done, call callback
    callback();
}

public void CallbackMethod()
{

}

I guess it would be done with Delegates, but not sure isnt there a simplier way here?
Thanks!

It sound like what you want are just raw C++ function pointers. You can learn more about them here

Hi. You can use Unreal delegates itself:

  • Declare your delegate type using DECLARE_DELEGATE_* macro family.
  • Declare your function somewhere you want: void FunctionWithCallback( FDelegateType Callback );
  • Call it then: FunctionWithCallback( FDelegateType::CreateSP( SharedThis( this ), some args ) );

A delegate could be created from function using static methods of created delegate type:

  • CreateSP makes a delegate bound to something placed into the shared pointer.
  • CreateStatic allow you to bound a delegate to the static function
  • CreateRaw allow to use a raw pointer to an object and it’s method as a function
  • CreateLambda allows to use c++ lambda functions
  • CreateUObject allows to bound delegate to a managed UObject

Also for simple callbacks you can use a function pointer style:

void FunctionWithCallback( void(*Callback)(int, float) ) { Callback(1, 2.0f); };
2 Likes

Nice!
Guys, thanks a lot!
This is exactly what I have been looking for!

Thanks a lot!

Glad I could help! Please mark one of the answers as correct, so this question is marked as solved.