为什么使用 IntPtr 作为句柄?
使用 PInvoke 时,我注意到我们需要使用 IntPtr
来引用 Windows 句柄。我想知道为什么不直接使用 int
作为句柄?我对句柄的理解是它只是一个整数值。
When using PInvoke, I noticed that we need to use IntPtr
to refer to Windows handles. I am wondering why not just use int
for the handle? My understanding of a handle is that it is just an integer value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Windows 句柄被定义为本机计算机指针大小的整数。这样,如果需要的话,他们可以秘密地充当指针。 (句柄可能不是指针,但如果操作系统实现者认为有必要,则允许是指针。出于安全原因,它们通常实际上不是指针;它如果它们实际上是指针,那么人们很容易滥用系统。)
C# 中的 int 定义为 32 位整数,在 64 位机器上它太小了。 IntPtr 被定义为可以保存机器大小的指针的整数。这就是为什么在与句柄互操作时始终使用 IntPtr 的原因。
A windows handle is defined as an integer of the native machine pointer size. That's so that they can secretly be a pointer if they need to be. (A handle probably is not a pointer, but it is permitted to be one if the operating system implementers deem it necessary. They typically are not actually pointers for security reasons; it makes it too easy for people to abuse the system if they are actually pointers.)
An int in C# defined as a 32 bit integer, which will be too small on a 64 bit machine. An IntPtr is defined as an integer that can hold a pointer of the machine size. That's why you always use IntPtr when interoperating with handles.
句柄是指针大小的值。
它们在 64 位平台上为 8 字节宽。
Handles are pointer-sized values.
They're 8 bytes wide on 64-bit platforms.
句柄的大小取决于机器架构(32/64 位)。
IntPtr
会处理这个问题。The size of a handle is dependant on the machine architecture (32/64 bit).
IntPtr
will take care of that.句柄本质上是一个系统级指针,并且指针不会隐式转换为 int。它本身就是一种类型。这就是为什么在 .NET 中使用
IntPtr
来表示 Handle 类型。A handle is essentially a system level pointer, and a pointer does not implicitly cast to an int. It is a type by itself. So that's why you have
IntPtr
in .NET to represent the Handle type.