c# - 算术运算导致溢出 c#

标签 c# winapi win32-process

解锁文件时出现以下错误

Arithmetic operation resulted in an overflow

System.IntPtr.ToInt32


我怀疑这是 pBuffer.ToInt32() 的以下行:
IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3)));
我自己无法重现该错误,并且该错误未显示正确的行号。我正在寻找一种方法来重现此问题或有关可能原因的任何反馈。谢谢
public void Close()
{
        const int MAX_PREFERRED_LENGTH = -1;
        int readEntries;
        int totalEntries;
        IntPtr pBuffer = IntPtr.Zero;
        FILE_INFO_3 fi3 = new FILE_INFO_3();
        int iStatus = NetFileEnum(this.HostName, this.HostPathToShare + this.FileNameFromShare, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out readEntries, out totalEntries, pBuffer);
        if (iStatus == 0)
        {
            for (int i = 0; i < readEntries; i++)
            {
                IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3)));
                fi3 = (FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(FILE_INFO_3));
                NetFileClose(this.HostName, fi3.fi3_id);
            }
        }
        NetApiBufferFree(pBuffer);
}

[DllImport("netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
static extern int NetFileClose(
    string servername,
    int id);

[DllImport("Netapi32.dll", SetLastError=true)]
static extern int NetApiBufferFree(IntPtr Buffer);

[DllImport("netapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern int NetFileEnum(
     string servername,
     string basepath,
     string username,
     int level,
     ref IntPtr bufptr,
     int prefmaxlen,
     out int entriesread,
     out int totalentries,
     IntPtr resume_handle
);
更新
我添加了 win32 apis 代码。
下面的答案看起来是正确的,机器是 64 位的。但是我无法在开发服务器上重现它,尽管开发环境是 64 位。任何想法来重现错误?

最佳答案

该错误是由您的代码在 64 位上下文中运行并返回位于 32 位可寻址范围之外的指针地址引起的,因此 .ToInt32() 抛出。

调用 Environment.Is64BitProcess 来检测你的进程是在 32 位还是 64 位上运行,并相应地转换地址:

long pointerAddress;

if (Environment.Is64BitProcess)
{
    pointerAddress = pBuffer.ToInt64(); 
}
else
{
    pointerAddress = pBuffer.ToInt32(); 
}

var fileInfoPointer = new IntPtr(pointerAddress + (i * Marshal.SizeOf(fi3)));

关于c# - 算术运算导致溢出 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36478303/

相关文章:

c++ - VirtualAlloc/Ex分配什么样的内存

c# - 不断增长的 .NET 项目的管理和结构

c# - 使用 C# 使用 Azure DevOps Rest API 创建工作项

c# - 在 C# 中将注册表项导出到 .REG 文件

c++ - 如何合并一个 pImpl 接口(interface),同时还允许 WndProc 与其交互?

c++ - EnumDisplayDevices 函数对我不起作用

C++ CALLBACK函数类型

c++ - 我如何使用 WinAPI 将消息发送到 Internet Explorer 9

c# - 如何使用 GLFW.Net 初始化 OpenGL.NET?

c# - 重命名 C# 项目以映射到正确的配置