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 处理时关闭句柄.SafeHandle
是一个抽象类,因为不同的 Win32 句柄有不同的关闭方式.在引入 SafeHandle
之前,IntPtr
用于保存 Win32 句柄,但确保它们正确关闭并防止被 GC 处理是程序员的责任.
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 处理的方法.如果没有像 HandleRef
这样的东西,如果您的托管代码在 P/Invoke 调用之后不对句柄做任何事情,如果在 P/Invoke 调用期间运行 GC,它就不会意识到句柄是仍在使用中,可能会 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屋!