6

I need to convert an UIntPtr object to that of IntPtr in my C# .NET 2.0 application. How can this be accomplished? I don't suppose it's as simple as this:

UIntPtr _myUIntPtr = /* Some initializer value. */
object _myObject = (object)_myUIntPtr;
IntPtr _myIntPtr = (IntPtr)_myObject;
svick
  • 236,525
  • 50
  • 385
  • 514
Jim Fell
  • 13,750
  • 36
  • 127
  • 202

3 Answers3

15

This should work on x86 and x64

IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    Unfortunately this does not appear to work on x86. I get an OverflowException with: `UIntPtr uintPtr = new UIntPtr(0xffffffffu); IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr);` – John Hall Aug 25 '16 at 12:43
2

This should work on 32 bit operating systems:

IntPtr intPtr = (IntPtr)(int)(uint)uintPtr;

That is, turn the UIntPtr into a uint, turn that into an int, and then turn that into an IntPtr.

Odds are good that the jitter will optimize away all the conversions and simply turn this into a direct assignment of the one value to the other, but I haven't actually tested that.

See Jared's answer for a solution that works on 64 bit operating systems.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
1
UIntPtr _myUIntPtr = /* Some initializer value. */ 
void* ptr = _myUIntPtr.ToPointer();
IntPtr _myIntPtr = new IntPtr(ptr);
Alex F
  • 42,307
  • 41
  • 144
  • 212