Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntPtr.ToInt32() and x64 systems

In my c# dll I have some code like this to interact with some unmanaged dlls:

IntPtr buffer = ...;
TTPOLYGONHEADER header = (TTPOLYGONHEADER)Marshal.PtrToStructure(
                       new IntPtr(buffer.ToInt32() + index), typeof(TTPOLYGONHEADER));

This has always worked fine when using my dll compiled in AnyCPU with .Net2 and .Net4 on x64 systems, before installing Windows 8.

With Windows 8 when using the .Net4 dll I get an OverFlowException ("Arithmetic operation resulted in an overflow.") at the buffer.ToInt32() call.

The MSDN documentation for IntPtr.ToInt32() says this:

"OverflowException: On a 64-bit platform, the value of this instance is too large or too small to represent as a 32-bit signed integer."

I wonder why this problem has surfaced only with Windows 8, and what is the correct way to fix it.

Should I use a method like this, instead of the IntPtr.ToInt32() call?

    internal static long GetPtr(IntPtr ptr)
    {
        if (IntPtr.Size == 4) // x86

            return ptr.ToInt32();

        return ptr.ToInt64(); // x64
    }
like image 760
devdept2 Avatar asked Sep 12 '12 14:09

devdept2


1 Answers

You shouldn't be calling any of the conversion functions just to add and offset and immediately convert back. IntPtr has two built-in ways to directly add an offset, either of

IntPtr.Add(buffer, index)

or simply

(buffer + index)

like image 149
Ben Voigt Avatar answered Sep 18 '22 04:09

Ben Voigt