Preventing unmanaged function pointer garbage collection

依然范特西╮ 提交于 2019-12-22 06:57:25

问题


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.



来源:https://stackoverflow.com/questions/17251754/preventing-unmanaged-function-pointer-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!