Been doing a little work on this and I've found a method that works, but I'm unsure about
:
a. How safe it is.
b. Is it the correct way to do it.
In my COM object I have:
-
public delegate void MyEventHandler ( object sender, SomeEventArgs args );
-
-
public interface IEventLibrary {
-
...
-
-
string DoSomething();
-
-
void AddHandler ( IntPtr addressOfHandler );
-
void RemoveHandler ( IntPtr addressOfHandler );
-
-
...
-
}
-
-
public class EventLibrary : IEventLibrary {
-
-
...
-
-
public event MyEventHandler MyEvent;
-
-
-
public void AddHandler ( IntPtr addressOfHandler ) {
-
MyEventHandler asDelegate = (MyEventHandler)Marshal.GetDelegateForFunctionPointer(addressOfHandler,typeof(MyEventHandler));
-
MyEvent += asDelegate;
-
}
-
-
-
public void RemoveHandler ( IntPtr addressOfHandler ) {
-
MyEventHandler asDelegate = (MyEventHandler)Marshal.GetDelegateForFunctionPointer(addressOfHandler,typeof(MyEventHandler));
-
MyEvent -= asDelegate;
-
}
-
-
-
public string DoSomething() {
-
if ( MyEvent != null ) {
-
MyEvent(this,new SomeEventArgs("SomeMessage"));
-
}
-
-
return "Doing Something";
-
}
-
-
...
-
}
-
-
public class SomeEventArgs : EventArgs {
-
...
-
}
-
And from the C++ program:
-
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) {
-
...
-
-
lib->AddHandler((long)SomeHandler);
-
-
lib->DoSomething();
-
-
// For this simple test, gDone is a global bool which gets set to true in the handler.
-
while ( !gDone ) {
-
;
-
}
-
-
lib->RemoveHandler((long)SomeHandler);
-
-
lib->Release();
-
...
-
}
-
-
-
void SomeHandler ( ) {
-
gDone = true;
-
}
-
-
This works and the handler is getting called.
I don't know what parameters are being passed to the handler - if any!
I've tried putting some void pointers in ( void SomeHandler ( void* sender, void* args) ) but they're null.
To me, this seems both right and wrong (mostly wrong :<).
Any advice or additional information would be appreciated.
Thanks in advance,
Andrew