[c++/CLI] let an unmanaged class consume an event

B

bonk

Hello,

I have a managed type that defines an Event as one of its public
members. Is it possible for an unmanaged c++ class to register to that
event ? How can an unmanaged classmethod be called as a response to a
raised event ?

Within my unmanaged class I tried to following:

void MyUnManagedClass::InitializeAndRegister ()
{
RefClass^ rc = gcnew RefClass();
rc->SomeEvent += gcnew SomeEventHandlerDelegate
(this,&MyUnManagedClass::OnEvent);
}
void MyUnManagedClass::OnEvent()
{
// do something as a response to the event here
}

unfortuantely I get the compilererror: C3364 : delegate constructor
argument must be pointer to memeber function of managed class or global
function

does that mean only managed classes can register themselfes to an event?
If so, do you see any workaround to make unmanaged classes register
respond to events?

Do you have a simple example ?
 
T

Tamas Demjen

bonk said:
Hello,

I have a managed type that defines an Event as one of its public
members. Is it possible for an unmanaged c++ class to register to that
event ? How can an unmanaged classmethod be called as a response to a
raised event ?

Do you have a simple example ?

This is the exact opposite of what we were trying to do in the thread
above ("UINT16 error"). There the sender was unmanaged and the handler
was managed. Here the sender is managed and the handler is unmanaged.
Here, too, we need to introduce a thunk to forward the call, only in
this case the Thunk must be a managed class, so it can handle the
managed event:

delegate void MyEvent(int);

ref class Managed
// event sender
{
public:
event MyEvent^ SomeEvent;
void FireEvent()
{
SomeEvent(10);
}
};

class Unmanaged
// event receiver
{
public:
void OnEvent(int i) { }
};

ref class Thunk
// event forwarder
{
public:
Unmanaged* c;
void CallbackHandler(int i) { c->OnEvent(i); }
};

void Test()
{
Unmanaged u;
Managed^ m = gcnew Managed;
Thunk^ thunk = gcnew Thunk;
thunk->c = &u;
m->SomeEvent += gcnew MyEvent(thunk, &Thunk::CallbackHandler);
m->FireEvent();
}

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top