preventing非托管函数指针的垃圾收集 [英] Preventing unmanaged function pointer garbage collection

查看:201
本文介绍了preventing非托管函数指针的垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文档转换代表,我负责preventing它收集自己非托管code状态。我想知道,如果代理人无法收集,同时非托管呼叫现场。举例来说,如果我这样做

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);

在这里UnmanagedFunction不存储函数指针超出它的调用。这应该是合法的,对不对?在CLR不能收集虽然UnmanagedFunction正在执行。

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.

推荐答案

根据 CLR内向外:编组之间的托管和非托管code

通常情况下,你会不会担心代表的使用寿命。每当你传递一个委托给非托管code, CLR将确保在通话过程中的委托是活着

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 不存储函数指针超出它的调用。

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

在本文中的下段

然而,如果本机code保持指针的拷贝超出通话范围,并打算再打通过该指针后,您可能需要使用的GCHandle 来显式prevent垃圾回收器回收的委托。

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.

做的没有的申请。

这篇关于preventing非托管函数指针的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆