小编dev*_*pt2的帖子

IntPtr.ToInt32()和x64系统

在我的c#dll中,我有一些像这样的代码与一些非托管的dll进行交互:

IntPtr buffer = ...;
TTPOLYGONHEADER header = (TTPOLYGONHEADER)Marshal.PtrToStructure(
                       new IntPtr(buffer.ToInt32() + index), typeof(TTPOLYGONHEADER));
Run Code Online (Sandbox Code Playgroud)

在安装Windows 8之前,在x64系统上使用AnyCPU中的.Net2和.Net4编译的dll时,这一直都能正常工作.

在使用.Net4 dll的Windows 8中,我在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
    }
Run Code Online (Sandbox Code Playgroud)

64-bit intptr overflowexception windows-8

7
推荐指数
1
解决办法
3209
查看次数

标签 统计

64-bit ×1

intptr ×1

overflowexception ×1

windows-8 ×1