【问题标题】:IntPtr.ToInt32() and x64 systemsIntPtr.ToInt32() 和 x64 系统
【发布时间】:2012-09-05 13:59:46
【问题描述】:

在我的 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
    }

【问题讨论】:

  • 总是使用 ToInt64()。或转换为(长)。
  • Hans Passant,请将其作为答案发布。

标签: windows-8 64-bit intptr overflowexception


【解决方案1】:

您不应该调用任何转换函数只是为了添加和偏移并立即转换回来。 IntPtr两种 内置方法可以直接添加偏移量,其中一种是

IntPtr.Add(buffer, index)

或者干脆

(buffer + index)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多