在我的 c# dll 中,我有一些这样的代码可以与一些非托管 dll 交互:
IntPtr buffer = ...;
TTPOLYGONHEADER header = (TTPOLYGONHEADER)Marshal.PtrToStructure(
new IntPtr(buffer.ToInt32() + index), typeof(TTPOLYGONHEADER));
在安装 Windows 8 之前,在 x64 系统上使用带有 .Net2 和 .Net4 的 AnyCPU 编译的 dll 时,这一直运行良好。
在 Windows 8 中使用 .Net4 dll 时,我在 buffer.ToInt32() 调用中收到 OverFlowException(“算术运算导致溢出。”)。
IntPtr.ToInt32() 的 MSDN 文档说:
“OverflowException:在 64 位平台上,此实例的值太大或太小,无法表示为 32 位有符号整数。”
我想知道为什么这个问题只出现在 Windows 8 中,以及修复它的正确方法是什么。
我应该使用这样的方法,而不是 IntPtr.ToInt32() 调用吗?
internal static long GetPtr(IntPtr ptr)
{
if (IntPtr.Size == 4) // x86
return ptr.ToInt32();
return ptr.ToInt64(); // x64
}