IntPtr的,的SafeHandle和HandleRef - 解释 [英] IntPtr, SafeHandle and HandleRef - Explained
问题描述
不指着我的MSDN,可能有人给出每种以及何时使用它们的目的的简洁,明确的解释。 (IntPtr的,的SafeHandle和HandleRef)
Without pointing me to MSDN, could someone give a concise, clear explanation of the purpose of each of these and when to use them. (IntPtr, SafeHandle and HandleRef)
推荐答案
的IntPtr
只是一个简单的基于整数的结构,可以容纳一个指针(即,32位大小在32位系统,在64位系统的64位大小)。
IntPtr
is just a simple integer-based struct that can hold a pointer (ie., 32 bit size on 32-bit systems, 64-bit size on 64-bit systems).
的SafeHandle
是一个类,是为了举办的Win32对象句柄 - 它有一个终结,使得确保当对象是GC'ed关闭句柄。 的SafeHandle
是一个抽象类,因为不同的Win32处理有他们需要被关闭不同的方式。在推出的SafeHandle
,的IntPtr
被用来装Win32的处理,但要确保他们正确关闭和$ p $被GC'ed是程序员的责任pvented。
SafeHandle
is a class that is intended to hold Win32 object handles - it has a finalizer that makes sure that the handle is closed when the object is GC'ed. SafeHandle
is an abstract class because different Win32 handles have different ways they need to be closed. Prior to the introduction of SafeHandle
, IntPtr
was used to hold Win32 handles, but ensuring that they were properly closed and prevented from being GC'ed was the responsibility of the programmer.
HandleRef
是一种方式,以确保当你在一个P的中/ Invoke调用非托管的句柄不会GC'ed。如果没有类似 HandleRef
,如果你的管理code并在P之后,不做与处理任何事情/ Invoke调用,如果GC是在P / Invoke的过程中运行把它不会意识到手柄仍在使用,可能GC它。我想(但我不知道,也没有看)的的SafeHandle
可以使用 HandleRef
作为其部分封装处理的管理。
HandleRef
is a way to make sure that an unmanaged handle is not GC'ed when you're in the middle of a P/Invoke call. Without something like HandleRef
, if your managed code doesn't do anything with the handle after the P/Invoke call, if the GC were run during the P/Invoke call it would not realize that the handle was still in use and might GC it. I imagine (but I'm not sure and haven't looked) that SafeHandle
might use HandleRef
as part of its management of the encapsulated handle.
这篇关于IntPtr的,的SafeHandle和HandleRef - 解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!