January 19, 2012

IntPtr Navigation

Have you ever wrote something like that?
IntPtr ptr=...
Marshal.PtrToStringUni((IntPtr)(ptr.ToInt32()+wDeviceOffset));

Such code is often necesary when invoking the Win32 API. Well this code works well unless you're not running this code on a x64 machine.
When running on a x64 machine you might get a nasty surprise as soon as the pointer's address is above int.MaxValue. To fix this problem you might use the following code.
IntPtr ptr=...
Marshal.PtrToStringUni(IntPtr.Add(ptr, wDeviceOffset));

There also exists a static Subtract method which let's you decrease the pointer's address.

No comments:

Post a Comment