问题
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;
回答1:
This should work on x86 and x64
IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr);
回答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.
回答3:
UIntPtr _myUIntPtr = /* Some initializer value. */ void* ptr = _myUIntPtr.ToPointer(); IntPtr _myIntPtr = new IntPtr(ptr);
来源:https://stackoverflow.com/questions/3762113/how-can-an-uintptr-object-be-converted-to-intptr-in-c