Marshal.PtrToStringUni(运行时)出现内存错误

时间:2018-12-16 09:32:20

标签: c#

我总是在此行出现错误(在运行时,而不是在编辑器中):

return Marshal.PtrToStringUni(ptr, object_TYPE_INFORMATION.Name.Length >> 1);

这是我的完整代码:

        public static string getObjectTypeName(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process)
    {
        IntPtr hSourceProcessHandle = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id);
        IntPtr zero = IntPtr.Zero;
        Win32API.OBJECT_BASIC_INFORMATION object_BASIC_INFORMATION = default(Win32API.OBJECT_BASIC_INFORMATION);
        IntPtr intPtr = IntPtr.Zero;
        Win32API.OBJECT_TYPE_INFORMATION object_TYPE_INFORMATION = default(Win32API.OBJECT_TYPE_INFORMATION);
        IntPtr intPtr2 = IntPtr.Zero;
        IntPtr zero2 = IntPtr.Zero;
        int num = 0;
        IntPtr ptr = IntPtr.Zero;
        bool flag = !Win32API.DuplicateHandle(hSourceProcessHandle, shHandle.Handle, Win32API.GetCurrentProcess(), out zero, 0u, false, 2u);
        string result;
        if (flag)
        {
            result = null;
        }
        else
        {
            intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<Win32API.OBJECT_BASIC_INFORMATION>(object_BASIC_INFORMATION));
            Win32API.NtQueryObject(zero, 0, intPtr, Marshal.SizeOf<Win32API.OBJECT_BASIC_INFORMATION>(object_BASIC_INFORMATION), ref num);
            object_BASIC_INFORMATION = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(intPtr, object_BASIC_INFORMATION.GetType());
            Marshal.FreeHGlobal(intPtr);
            intPtr2 = Marshal.AllocHGlobal(object_BASIC_INFORMATION.TypeInformationLength);
            num = object_BASIC_INFORMATION.TypeInformationLength;
            while (Win32API.NtQueryObject(zero, 2, intPtr2, num, ref num) == -1073741820)
            {
                Marshal.FreeHGlobal(intPtr2);
                intPtr2 = Marshal.AllocHGlobal(num);
            }
            object_TYPE_INFORMATION = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(intPtr2, object_TYPE_INFORMATION.GetType());
            bool flag2 = Win32Processes.Is64Bits();
            if (flag2)
            {
                ptr = new IntPtr(Convert.ToInt64(object_TYPE_INFORMATION.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ptr = object_TYPE_INFORMATION.Name.Buffer;
            }
            Marshal.FreeHGlobal(intPtr2);
        }
        return Marshal.PtrToStringUni(ptr, object_TYPE_INFORMATION.Name.Length >> 1);
    }

错误:

  

System.AccessViolationException:'试图读取或写入受保护的内存。这通常表明其他内存已损坏。'

.NET Framework版本:4.6.1

我在做什么错了?

0 个答案:

没有答案