How can I convert a UIntPtr object to IntPtr in C #?

I need to convert a UIntPtr object to an IntPtr object in my C # .NET 2.0 application. How can I do that? I don’t think it is that simple:

 UIntPtr _myUIntPtr = /* Some initializer value. */ object _myObject = (object)_myUIntPtr; IntPtr _myIntPtr = (IntPtr)_myObject; 
+6
object casting c #
source share
3 answers

This should work on x86 and x64

 IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr); 
+15
source share

This should work on 32-bit operating systems:

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

That is, turn UIntPtr into uint, turn it into int, and then turn it into IntPtr.

It's good that jitter optimizes all conversions and just turns it into a direct assignment of one value to another, but I haven't really tested it.

See the Jared answer for a solution that runs on 64-bit operating systems.

+2
source share
  UIntPtr _myUIntPtr = / * Some initializer value.  * / 
 void * ptr = _myUIntPtr.ToPointer ();
 IntPtr _myIntPtr = new IntPtr (ptr);
0
source share

All Articles