IntPtr.ToInt32 () and x64 systems

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

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

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

On Windows 8, when using DLL.Net4, I get an OverFlowException ("Arithmetic operation overflows") in a call to buffer.ToInt32 ().

The MSDN documentation for IntPtr.ToInt32 () says the following:

"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 appeared only with Windows 8, and how to fix it correctly.

Should I use such a method instead of calling IntPtr.ToInt32 ()?

  internal static long GetPtr(IntPtr ptr) { if (IntPtr.Size == 4) // x86 return ptr.ToInt32(); return ptr.ToInt64(); // x64 } 
+7
source share
1 answer

You should not call any conversion functions just to add and offset and immediately convert back. IntPtr has two built-in methods for directly adding an offset, either from

IntPtr.Add(buffer, index)

or simply

(buffer + index)

+1
source

All Articles