【问题标题】:System.OverflowException when casting a System.IntPtr to a uint将 System.IntPtr 转换为 uint 时出现 System.OverflowException
【发布时间】:2018-12-28 17:41:28
【问题描述】:

我试图将MaximumApplicationAddressSystemInfo 保存到uint,但我得到了System Overflow Exception

System.OverflowException:算术运算导致溢出

我尝试了很多,也搜索了很多,但没有任何帮助。如果我转换或使用小数,则无济于事。

这是有问题的代码:

private uint _maxAddress;

public MemorySearch()
{
    SystemInfo info;
    GetSystemInfo(out info);

    // This line throws a System.OverflowException:
    _maxAddress = (uint)info.MaximumApplicationAddress;
    resetFields();
}

Full Source Code Here

这是错误的屏幕截图:

有什么想法吗?

【问题讨论】:

  • 发布源代码截图通常是不好的做法。

标签: c# overflowexception


【解决方案1】:

编译器告诉您MaximumApplicationAddress 的大小大于uint

尝试改用long(64 位整数):

private long _maxAddress;

public MemorySearch()
{
    SystemInfo info;
    GetSystemInfo(out info);

    _maxAddress = info.MaximumApplicationAddress.ToInt64();
    resetFields();
}

【讨论】:

  • 变量观察窗格显示MaximumApplicationAddress 的值为0x00007ffffffeffff(在base-10 中为140,737,488,289,791)。这超出了uint 的范围。在long 中存储价值。
【解决方案2】:

没有从IntPtruint (UInt32) 的显式或隐式转换。有一个到Int32 的显式转换。见https://docs.microsoft.com/en-us/dotnet/api/system.intptr.op_explicit?view=netframework-4.7.2#System_IntPtr_op_Explicit_System_IntPtr__System_Int32

如果您在 64 位系统上调用该函数,则会抛出 OverflowException

如果您真的想将 64 位指针转换为 32 位值,则必须先转换为 ulong,然后再转换为 uint

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2013-03-05
    • 2012-11-06
    • 2014-07-31
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多