user705414
user705414

Reputation: 21200

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.

Upvotes: 10

Views: 3500

Answers (4)

SLaks
SLaks

Reputation: 887453

Handles are pointer-sized values.

They're 8 bytes wide on 64-bit platforms.

Upvotes: 10

Eric Lippert
Eric Lippert

Reputation: 660098

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.

Upvotes: 18

Eugen Rieck
Eugen Rieck

Reputation: 65274

The size of a handle is dependant on the machine architecture (32/64 bit). IntPtr will take care of that.

Upvotes: 4

Tony The Lion
Tony The Lion

Reputation: 63200

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.

Upvotes: 2

Related Questions