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.

About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 50 other followers

%d bloggers like this: