System.OverflowException when casting a System.IntPtr to a uint

1.3k Views Asked by At

I tried to save the MaximumApplicationAddress from SystemInfo into an uint, but I get a System Overflow Exception:

System.OverflowException: The arithmetic operation caused an overflow

I tried a lot and also googled a lot, but nothing helps. If I convert or if I use an decimal, nothing helped.

Here is the problematic code:

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

Here's a screenshot of the error:

Screenshot

Any ideas?

2

There are 2 best solutions below

1
Rufus L On

The compiler is telling you that the size of MaximumApplicationAddress is larger than a uint.

Try using a long (64-bit integer) instead:

private long _maxAddress;

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

    _maxAddress = info.MaximumApplicationAddress.ToInt64();
    resetFields();
}
0
Jim Mischel On

There is no explicit or implicit conversion from IntPtr to uint (UInt32). There is an explicit conversion to Int32. See https://learn.microsoft.com/en-us/dotnet/api/system.intptr.op_explicit?view=netframework-4.7.2#System_IntPtr_op_Explicit_System_IntPtr__System_Int32.

That function throws OverflowException if you call it on a 64-bit system.

If you really want to turn your 64-bit pointer into a 32-bit value, then you'll have to cast to a ulong, and then to a uint.