将委托(delegate)转换为非托管代码的文档指出我有责任自行防止它被收集。我想知道在非托管调用处于事件状态时是否无法收集委托(delegate)。例如,如果我这样做
UnmanagedFunction(arg => somebody);
其中 UnmanagedFunction 不存储调用之外的函数指针。这应该是合法的吧? CLR 无法在 UnmanagedFunction 执行时进行收集。
最佳答案
根据 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.
看来你还好。
因为你明确提到
UnmanagedFunction
does not store the function pointer beyond it's invocation.
文章的下一段
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.
不适用。
关于c# - 防止非托管函数指针垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251754/