c# - 防止非托管函数指针垃圾回收

标签 c# .net delegates garbage-collection clr

将委托(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/

相关文章:

ios - 未调用委托(delegate)方法并给出 nil 值

c# - 为项目添加资源的设计

c# - 使用 Math.Pow(10, n) 可以吗?

c# - <nativehr>0x80070057</nativehr><nativestack></nativestack> 在 Sharepoint 列表中创建选择字段时

.net - 如何处理 System.Data.DataTableExtensions.CopyToDataTable() 中的缺陷

ios - 在 Xcode beta 4 中设置 UITableViewCell 委托(delegate)时崩溃

c# - 模拟事件处理器

c# - 如何按值列表分组,然后计算每个值的条目数量

c# - 'NHibernate.Spatial.Type.GeometryType' 处理的“GeoAPI.Geometries.IGeometry”不可序列化

c# - 获取两种颜色 HEX refs 或 RGB 之间的颜色