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.
![](../../users/profiles/412770.webp)
- 103,292
- 21
- 241
- 294
![](../../users/profiles/705414.webp)
- 17,800
- 36
- 105
- 151
-
7Your making the most common mistake that causes x64 incompatibilities. – SLaks Feb 07 '12 at 00:24
-
5Sure, they're integer values. But no one said they have to be 32 bits... – user541686 Feb 07 '12 at 00:25
4 Answers
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.
![](../../users/profiles/88656.webp)
- 612,321
- 166
- 1,175
- 2,033
Handles are pointer-sized values.
They're 8 bytes wide on 64-bit platforms.
![](../../users/profiles/34397.webp)
- 800,742
- 167
- 1,811
- 1,896
-
1I'd say "pointer-*sized*" instead of "pointer" (even though I guess in the strict C/C++ sense, that isn't too accurate, since handles are `typedef`'d as a pointer all right, and `size_t` isn't necessarily the size of a pointer)... but if they're indices into a table, chances are they're used as integers. But yeah, point taken. – user541686 Feb 07 '12 at 00:26
The size of a handle is dependant on the machine architecture (32/64 bit). IntPtr
will take care of that.
![](../../users/profiles/1100552.webp)
- 60,102
- 9
- 66
- 89
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.
![](../../users/profiles/174614.webp)
- 57,181
- 57
- 223
- 390