Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using IntPtr for handle?

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.

like image 790
user705414 Avatar asked Feb 07 '12 00:02

user705414


People also ask

What is the use of IntPtr in C#?

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.

How does IntPtr work?

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.


1 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.

like image 68
Eric Lippert Avatar answered Nov 08 '22 19:11

Eric Lippert