internal static byte[] PatchCode(IntPtr Offset, byte[] Code)
{
byte[] OldCode = new byte[Code.Length];
IntPtr Written;
IntPtr CodeBuffer;
//
// Save a copy of the original code, allocate an intermediate
// fixed bounce buffer, copy to the bounce buffer, and write the
// new code in (WriteProcessMemory will manage reprotection as
// required).
//
Marshal.Copy(Offset, OldCode, 0, OldCode.Length);
CodeBuffer = Marshal.AllocHGlobal(Code.Length);
try
{
Marshal.Copy(Code, 0, CodeBuffer, Code.Length);
if (WriteProcessMemory(GetCurrentProcess(), Offset, CodeBuffer, new IntPtr(Code.Length), out Written) == 0 || (int)Written != Code.Length)
{
throw new InvalidOperationException("Couldn't write process memory.");
}
}
finally
{
Marshal.FreeHGlobal(CodeBuffer);
}
return OldCode;
}
}