用于读取带偏移量的内存值的通用方法

问题描述 投票:1回答:1
[DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")]
public static extern int ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, 
                                          [In, Out] byte[] buffer, int size, out IntPtr lpNumberOfBytesRead);

private byte[] ReadBytes(Process process, MemoryAddress address, int bytesToRead)
{
    var value = new byte[bytesToRead];
    var baseAddress = GetBaseAddressByModuleName(process, address.Module.Value) + address.BaseAddress;
    var handle = GetProcessHandle(process);

    ReadProcessMemory(handle, (IntPtr)baseAddress, value, bytesToRead, out var bytesRead);

    foreach (var offset in address.Offsets)
    {
        ReadProcessMemory(handle,
            new IntPtr(BitConverter.ToInt32(value, 0) + offset),
            value,
            bytesToRead,
            out bytesRead);
    }

    return value;
}

private static int GetSize<T>()
{
    return Marshal.SizeOf(typeof(T));
}

这与float,int,double和string一起使用都很好:

public long ReadLong(Process process, MemoryAddress address)
{
    return ReadBytes(process, address, GetSize<long>()).ConvertTo<long>();
}

这是我的问题(ConvertTo只是使用BitConverter的扩展名。):

public short ReadShort(Process process, MemoryAddress address)
{
    return ReadBytes(process, address, GetSize<short>()).ConvertTo<short>();
}

public byte ReadByte(Process process, MemoryAddress address)
{
    return ReadBytes(process, address, 1)[0];
}

使用这些方法时,在ReadBytesSystem.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length.'的foreach循环中引发异常。>

我想它与BitConverter.ToInt32有关。将ToInt16用作short会摆脱异常,但会产生错误的结果。如何正确处理带有偏移的shortbyte值?

[DllImport(“ kernel32.dll”,EntryPoint =“ ReadProcessMemory”)]公共静态外部int ReadProcessMemory(IntPtr hProcess,IntPtr lpBaseAddress,[In,Out] ...

c# pinvoke
1个回答
0
投票

我知道您现在正在做什么-您正在遵循一系列对象引用,以引用存储在最后一个对象中的值。这样的事情应该适用于32位地址指针,这听起来像是您正在做的事情:

© www.soinside.com 2019 - 2024. All rights reserved.