views:

82

answers:

3

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;

Thanks.

A: 
UIntPtr _myUIntPtr = /* Some initializer value. */ 
void* ptr = _myUIntPtr.ToPointer();
IntPtr _myIntPtr = new IntPtr(ptr);
Alex Farber
`UIntPtr x2 = new UIntPtr(x.ToPointer());` does work, but only in an unsafe context.
Brian
+1  A: 

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
Does this also work if `UIntPtr.Size != 4`?
dtb
This is *not* okay, it destroys the pointer in 64-bit mode. Use long/ulong.
Hans Passant
Excellent point, thanks!
Eric Lippert
+5  A: 

This should work on x86 and x64

IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr);
JaredPar