Hi, using a delegate to handle an event im getting from an api call, only problem is its being destroyed by GC and not sure how to stop this ..
private delegate void StartStopEventDelegate(short Channel, short Event);
[DllImport("c:\\mydll.dll")]
private static extern char SetCallBack_StartStop(StartStopEventDelegate myDelegate);
then use of above code which is done i
SetCallBack_StartStop(startstop);
void startstop(short channel, short event)
{
//lotsa stuff here
}
after i force GC or wait for GC i get
A callback was made on a garbage collected delegate of type
please help
Stoping delegate from getting gc'ed
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.

AlanRank #669 · 3.6K reputationPosted Aug 1, 2007, 1:48 PM EDT
I'd try 'pinning' the delegate with this line before you make the call:
GCHandle gch = GCHandle.Alloc(startstop, GCHandleType.Pinned);
and when you're finished unpin it and release the handle with:
gch.Free();
Daniel van Pletzen25 reputationPosted Aug 1, 2007, 2:08 PM EDT
Mike GoldRank #50 · 30.6K reputationPosted Aug 1, 2007, 2:15 PM EDT
You might consider doing this PInvoke piece in a separate assembly using managed c++. Managed C++ is a bit more forgiving with unmanaged calls. Here is a link that shows you how to do it.
http://msdn2.microsoft.com/en-us/library/ektebyzx(VS.80).aspx