Preventing unmanaged function pointer garbage coll

2019-05-02 12:10发布

问题:

The documentation for converting delegates to unmanaged code states that I am responsible for preventing it's collection myself. I wish to know if the delegate cannot be collected whilst the unmanaged call is live. For example, if I do

UnmanagedFunction(arg => somebody);

where UnmanagedFunction does not store the function pointer beyond it's invocation. This should be legal, right? The CLR can't collect whilst the UnmanagedFunction is executing.

回答1:

According to CLR Inside Out: Marshaling between Managed and Unmanaged Code:

Usually, you won't have to worry about the lifetime of delegates. Whenever you are passing a delegate to unmanaged code, the CLR will make sure the delegate is alive during the call.

Seems you're okay.

Since you explicitly mention

UnmanagedFunction does not store the function pointer beyond it's invocation.

the next paragraph in the article

However, if the native code keeps a copy of the pointer beyond the span of the call and intends to call back through that pointer later, you might need to use GCHandle to explicitly prevent the garbage collector from collecting the delegate.

does not apply.