How to keep the reference to a delegate registered to a native API function

When you call a Win32 native function from C# using P/Invoke, there are times when the Win32 function requires a callback for various purpose like callback for status feedback.

Then, the callback functions are expected to be called repeatedly until it is unregistered.
However, the garbage collector frees up the callback function. ( It’s a delegate. )

Then how to prevent it from being collected?

Here is a nice blog post about it.
beefycode : Delegates and Native API Callbacks – Answer

In short, it is to declare a member variable to the delegate to make the subordinating class keep the reference to it.

Leave a comment