Jim Fell
Jim Fell

Reputation: 14254

How can an UIntPtr object be converted to IntPtr in C#?

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;

Upvotes: 6

Views: 4868

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660159

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.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754893

This should work on x86 and x64

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

Upvotes: 15

Alex F
Alex F

Reputation: 43321

UIntPtr _myUIntPtr = /* Some initializer value. */ 
void* ptr = _myUIntPtr.ToPointer();
IntPtr _myIntPtr = new IntPtr(ptr);

Upvotes: 1

Related Questions