How to fix “Access Violation Exception” when accessing ImageHlp.MapFileAndCheckSumA? [duplicate]

a 夏天 提交于 2020-06-29 03:54:47

问题


I declare it as:

        [System.Runtime.InteropServices.DllImport("imagehlp.dll")]

        public static extern UInt32 MapFileAndCheckSumA(string fileName,
            IntPtr HeaderSum,
            IntPtr CheckSum);

Then I try to call MapFileAndCheckSumA

        IntPtr HeaderSum = new IntPtr(0);
        IntPtr CheckSum = new IntPtr(0);
        UInt32 status= ImageHlp.MapFileAndCheckSumA("19_02_21.exe", HeaderSum, CheckSum);

        Console.WriteLine(status);
        Console.WriteLine(CheckSum.ToInt32());
        Console.ReadLine();

But I get this error pointing to ImageHlp.MapFileAndCheckSumA(.....):

System.AccessViolationException
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

I think I have done a very simple but obvious mistake.

Correction: The error was thrown because my code above was trying to allocate at memory location 0x0.

The proper way of using IntPtr() is:

    int HeaderSum = 0;
    int CheckSum = 0;
    IntPtr ptrHeaderSum=Marshal.AllocHGlobal(sizeof(int));
    Marshal.WriteInt32(ptrHeaderSum, HeaderSum);
    IntPtr ptrCheckSum = Marshal.AllocHGlobal(sizeof(int));
    Marshal.WriteInt32(ptrCheckSum, CheckSum);
    UInt32 status= ImageHlp.MapFileAndCheckSumA(@"D:\19_02_21.exe", ptrHeaderSum, ptrCheckSum);

    Console.WriteLine(status);
    CheckSum = Marshal.ReadInt32(ptrCheckSum);
    Console.WriteLine(CheckSum);

    Marshal.FreeHGlobal(ptrHeaderSum);
    Marshal.FreeHGlobal(ptrCheckSum);
    Console.ReadLine();

来源:https://stackoverflow.com/questions/62302373/how-to-fix-access-violation-exception-when-accessing-imagehlp-mapfileandchecks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!