65.9K
CodeProject is changing. Read more.
Home

Yet another approach to Delegates in unmanaged C++

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.78/5 (9 votes)

Mar 6, 2002

viewsIcon

95283

downloadIcon

587

Asynchronous delegates in unamanaged C++ using the C# syntax

Sample Image - cppDelegate.gif

Introduction

Ben Chan introduced a way of simulating delegates in unmanaged code. Although his method works I wanted to have a syntax similar found in the C# language. I also wanted to be able to use async delegates.

Using my solution

Defining a Delegate is simple as this:

Delegate OnBtnClick;
AsyncDelegate OnNewMail;

To add a new delegate handler to those defined above you have to choose whether you want to use a static/global function or a member function. To subscribe a delegate you use a syntax similar to C#'s:

class MyClass
{
public:
	void Handler1(LPVOID source, DelegateArgs* args)
	{
	...
	}

	static void StaticHandler(LPVOID source, DelegateArgs* args)
	{
	...
	}
};

void main()
{
	MyClass instance;
	Delegate OnBtnClick;

	OnBtnClick += NewClassDelegateHandler(MyClass, instance, Handler1);
	OnBtnClick += NewDelegateHandler(&MyClass::StaticHandler);


	LPVOID source = 0;
	DelegateArgs* args = 0;

	// you can also remove a delegate handler from the invocation list
	// OnBtnClick -= NewClassDelegateHandler(MyClass, instance, Handler1);

	OnBtnClick.Invoke(source, args);
}

NewClassDelegateHandler and NewDelegateHandler are defines that create the appropriate DelegateHandler class. It can be the StaticDelegateHandler for static functions or ClassDelegateHandler for member functions.

The async delegate only overrides the Delegate::Invoke method by creating a thread to invoke the handlers. You can make your delegate thread safe (AsyncDelegate already is) by defining a Delegate like this Delegate ThreadSafeDelegate(true);

IMPORTANT: To use my solution you have to enable runtime type information in your project.