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.
The IntPtr type can be used by languages that support pointers and as a common means of referring to data between languages that do and do not support pointers. IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.
An IntPtr is an integer which is the same size as a pointer. You can use IntPtr to store a pointer value in a non-pointer type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With