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

Generic method for reading memory values with offsets

[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 和字符串一起工作正常:

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];
}

当使用这些方法时,在 ReadBytes 的 foreach 循环中抛出异常:System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length.'

我认为它与 BitConverter.ToInt32 有关。将 ToInt16 用于 short 可以消除异常,但会产生错误的结果。如何正确处理 shortbyte 值的偏移量?

我明白你现在在做什么 - 你正在跟踪一系列对象引用,这些对象引用存储在最后一个对象中的值。像这样的东西应该适用于 32 位地址指针,这听起来就像你在做的那样:

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

    ReadProcessMemory(handle, (IntPtr)baseAddress, currentAddress, 4, out var bytesRead);

    foreach (var offset in address.Offsets.Take(address.Offsets.Length - 1))
    {
        ReadProcessMemory(handle,
            new IntPtr(BitConverter.ToInt32(currentAddress, 0) + offset),
            currentAddress,
            4,
            out bytesRead);
    }

    ReadProcessMemory(handle,
        new IntPtr(BitConverter.ToInt32(currentAddress, 0) + address.Offsets.Last()),
        value,
        bytesToRead,
        out bytesRead);

    return value;
}