Passing Delegates to Unmanaged Code

Adam Nathan writes about the issues with passing delegates to unmanaged code.  Namely: it can get garbage collected right out from under the unmanaged code:

The most common mistake made when passing a delegate to unmanaged code (marshaled as a function pointer) is to allow the delegate to be garbage collected before unmanaged code is finished using it. This can happen because unmanaged code is invisible to the CLR garbage collector; it has no way to know when a delegate might still be in use by unmanaged clients. Once the delegate is not being referenced by any managed code, it could be collected at any time, causing the function pointer to become invalid.

No Comments