Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing unmanaged function pointer garbage collection

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.

like image 357
Puppy Avatar asked Oct 03 '22 18:10

Puppy


1 Answers

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.

like image 188
jason Avatar answered Oct 11 '22 13:10

jason