1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| using System; using System.Diagnostics; using System.Runtime.InteropServices;
namespace SCPSLhax { public class Memory { public static Process Process; public static IntPtr ProcessHandle;
public static ProcessModule GameAssemblyModule;
public static int m_iBytesRead = 0; public static int m_iBytesWrite = 0;
public static T ReadMemory<T>(long Adress) where T : struct { int ByteSize = Marshal.SizeOf(typeof(T)); byte[] buffer = new byte[ByteSize]; Kernel32.ReadProcessMemory(ProcessHandle, (IntPtr)Adress, buffer, buffer.Length, ref m_iBytesRead);
return ByteArrayToStructure<T>(buffer); }
public static void WriteMemory<T>(long Adress, object Value) { byte[] buffer = StructureToByteArray(Value);
Kernel32.WriteProcessMemory(ProcessHandle, (IntPtr)Adress, buffer, buffer.Length, out m_iBytesWrite); }
public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct { var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } }
public static byte[] StructureToByteArray(object obj) { int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, len); Marshal.FreeHGlobal(ptr);
return arr; } } }
|