First a background question:
In general, what is the difference between int and IntPtr? My guess is that it is an actual object rather than a value like an int or byte is. Assuming that is true:
So they are not the same. Yet I see handles represented as both.
- IntPtr:
Control.Handle -
int (or uint): A PInvoke can be setup to return an
intand it works just fine:[DllImport("coredll.dll", SetLastError = true)] public static extern int GetForegroundWindow(); private string GetActiveWindow() { const int nChars = 256; int handle = 0; StringBuilder Buff = new StringBuilder(nChars); handle = CoreDLL.GetForegroundWindow(); if (CoreDLL.GetWindowText(handle, Buff, nChars) > 0) { return Buff.ToString(); } return ""; }
So, int vs IntPtr? Does it matter for handles? Can you use either?
intis 32 bits long.IntPtris as long as a pointer for your architecture. Therefore, a pointer can be stored into anintonly on 32 bit systems, while it can always be stored in anIntPtr.Notice that your “int as a return value” example does not use an
intto hold a pointer, but just to hold a numeric value. This does not mean that anintis automatically the correct size though: the author of that P/Invoke signature should have gone to the documentation forGetForegroundWindowand see that it returns aHWND.Then, from
windef.hin the Platform SDK (or this MSDN page) we can see that aHWNDis aHANDLEwhich is aPVOIDwhich is… a pointer!Therefore, as far as I can tell, that signature is wrong, as the size of the return value of
GetForegroundWindowdepends on the architecture. Thus, it should also be anIntPtr.Update:
While it can be inferred from the above, I think it’s worthwhile to explicitly point out that:
intinstead ofIntPtrin 32-bit applications will never cause a problem, even if they run on 64-bit Windows; since most applications are 32-bit at this point in time, this will let you get away such mistakes very often.intinstead ofIntPtrin 64-bit applications is not guaranteed to cause problems, since it is quite possible that in practice the values being encountered will fit in the 32 bits of theint. This further lessens the probability that a mistake will manifest as an application error.Therefore, for an error to actually manifest there are three conditions that have to be satisfied at the same time:
intis used where anIntPtrshould be.intis actually larger than 32 bits.