Callback in C++

Here is a simple way to initate a callback in C++ and CSharp

From app1.cpp the event will be invoked and will call a function in app2.cpp.
app1.cpp have no idea who app2.cpp. It just knows that it fired an event and it doesn't know will take care of the event which is in our case it's app2.cpp. (loose coupling).

App1.h
=======

1. First declare your stdcall:

typedef int (__stdcall * PCallback) (int id);


2. In Class create the prototype to set the callback

class App1Class
{
public:
void SetCallback(PCallback pCallBack);

private:
PCallback m_pCallback;
}


App1.cpp
============

void App1Class::SetCallback(PCallback pCallback)
{
m_pCallback = pCallback;
}


In the function where you want your callback to be fired, just call m_pCallback.
Let's say when a value is updated or when it reach a certain line.
=======================================================
m_pCallback(ID);


App2.cpp
=======

1. Create an instance of the App1Class

App1Class ac = new App1Class();

ac.SetCallback(funcApp2Callback); <--- What function you want to call in case the callback happens.



The function to accept the callback
==========================
int __stdcall ClassName::funcApp2Callback(MsgId id)
{
printf("App1Callback has been triggered!");
}


//////////////////////////////////////////////
As you can see App1 did not create an instance of App2 but was able to inform App2 that something has happened in App1. One advantage of this is that it can also inform App3 or App4 about the event without App1 knowing them. App3 and App4 just needs to register the callback.


Here is a CSharp version (much simpler)
=============================

using System;

delegate void OperationDelegate();

class TestDelegate
{
OperationDelegate funcPointer;
public TestDelegate()
{
}
public static void Foo()
{
Console.WriteLine("Foo was called by a delegate!");
}
public void setCallback(OperationDelegate NewFuncPointer)
{
funcPointer = new OperationDelegate(NewFuncPointer);
}

public static void Main()
{
TestDelegate t = new TestDelegate();
t.setCallback(Foo);
t.funcPointer();
}
}

コメント

人気の投稿