using System;
using ProcessNET.Marshaling;
using ProcessNET.Native.Types;
using ProcessNET.Utilities;
namespace ProcessNET.Memory
{
///
/// Class for memory editing a process.
///
///
public class ExternalProcessMemory : ProcessMemory
{
///
/// Initializes a new instance of the class.
///
/// The open handle to the process which contains the memory of interest.
public ExternalProcessMemory(SafeMemoryHandle handle) : base(handle)
{
}
///
/// Writes a set of bytes to memory.
///
/// The address where the bytes start in memory.
/// The length of the byte chunk to read from the memory address.
///
/// The byte array section read from memory.
///
public override byte[] Read(IntPtr intPtr, int length)
{
return MemoryHelper.ReadBytes(Handle, intPtr, length);
}
///
/// Writes a set of bytes to memory.
///
/// The address where the bytes start in memory.
/// The buffer to read data onto, it's size determines the count of bytes to read.
public override void Read(IntPtr intPtr, byte[] buffer)
{
MemoryHelper.ReadBytes(Handle, intPtr, buffer);
}
///
/// Reads the value of a specified type from memory.
///
/// The type of the value.
/// The address where the value is read.
/// A value.
public override T Read(IntPtr intPtr)
{
int size = MarshalCache.Size;
if (typeof(T) == typeof(IntPtr))
size = Is32Bit ? 4 : 8;
return MarshalType.ByteArrayToObject(Read(intPtr, size));
}
///
/// Writes the values of a specified type to memory.
///
/// The type of the value.
/// The address where the value is written.
/// The value to write.
public override void Write(IntPtr intPtr, T value)
{
Write(intPtr, MarshalType.ObjectToByteArray(value));
}
///
/// Write an array of bytes in the remote process.
///
/// The address where the array is written.
/// The array of bytes to write.
public override int Write(IntPtr intPtr, byte[] bytesToWrite)
{
using (new MemoryProtection(Handle, intPtr, MarshalType.Size * bytesToWrite.Length))
MemoryHelper.WriteBytes(Handle, intPtr, bytesToWrite);
return bytesToWrite.Length;
}
}
}