算术运算导致C#溢出

H20*_*der 0 c# winapi win32-process

解锁文件时出现以下错误

算术运算导致溢出

System.IntPtr.ToInt32

我怀疑这是以下行pBuffer.ToInt32()

IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3)));
Run Code Online (Sandbox Code Playgroud)

我自己无法重现该错误,并且该错误未显示正确的行号。我正在寻找一种方法来重现此问题或对可能原因的任何反馈。谢谢

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
);
Run Code Online (Sandbox Code Playgroud)

更新资料

我添加了win32 api代码。

以下答案看起来正确,并且该机器是64位的。但是,尽管开发环境为64位,但我无法在开发服务器上重现它。有什么想法可以重现错误吗?

Cod*_*ter 5

该错误是由于您的代码在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)));
Run Code Online (Sandbox Code Playgroud)