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

孤者浪人 提交于 2019-12-30 08:51:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!