using System;
using System.Text;
using Process.NET.Native.Types;
namespace Process.NET.Memory
{
///
/// Class for memory editing a process.
///
///
public abstract class ProcessMemory : IMemory
{
///
/// The open handle to the process which contains the memory of interest,
///
protected readonly SafeMemoryHandle Handle;
///
/// Initializes a new instance of the class.
///
/// The open handle to the process which contains the memory of interest.
protected ProcessMemory(SafeMemoryHandle handle)
{
Handle = 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 abstract byte[] Read(IntPtr intPtr, int length);
///
/// Reads a string with a specified encoding from memory.
///
/// The address where the string is read.
/// The encoding used.
///
/// The number of maximum bytes to read. The string is automatically cropped at this end ('\0'
/// char).
///
/// The string.
public string Read(IntPtr intPtr, Encoding encoding, int maxLength)
{
var buffer = Read(intPtr, maxLength);
var ret = encoding.GetString(buffer);
if (ret.IndexOf('\0') != -1)
ret = ret.Remove(ret.IndexOf('\0'));
return ret;
}
///
/// Reads the value of a specified type from memory.
///
/// The type of the value.
/// The address where the value is read.
/// A value.
public abstract T Read(IntPtr intPtr);
///
/// Reads an array of a specified type from memory.
///
/// The type of the values.
/// The address where the values is read.
/// The number of cells in the array.
/// An array.
public T[] Read(IntPtr intPtr, int length)
{
var buffer = new T[length];
for (var i = 0; i < buffer.Length; i++)
buffer[i] = Read(intPtr);
return buffer;
}
///
/// Write an array of bytes in the remote process.
///
/// The address where the array is written.
/// The array of bytes to write.
public abstract int Write(IntPtr intPtr, byte[] bytesToWrite);
///
/// Writes a string with a specified encoding to memory.
///
/// The address where the string is written.
/// The text to write.
/// The encoding used.
public virtual void Write(IntPtr intPtr, string stringToWrite, Encoding encoding)
{
if (stringToWrite[stringToWrite.Length - 1] != '\0')
stringToWrite += '\0';
var bytes = encoding.GetBytes(stringToWrite);
Write(intPtr, bytes);
}
///
/// Writes an array of a specified type to memory,
///
/// The type of the values.
/// The address where the values is written.
/// The array to write.
public void Write(IntPtr intPtr, T[] values)
{
foreach (var value in values)
Write(intPtr, value);
}
///
/// 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 abstract void Write(IntPtr intPtr, T value);
}
}