重新发一下,之前的不知道为什么有乱码
[C#] 纯文本查看 复制代码 using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
/////////////////////////使用例子/////////////////////////////////
//f(a,b,c) = a*b+c
byte[] MulAdd_int64 =
{
0x55, //push rbp
0x0f,0xaf,0xca, //imul rcx,rdx
0x49,0x01,0xc8, //add r8,rcx
0x49,0x8b,0xc0, //mov rax,r8
0x5D, //pop rbp
0xC3 //ret
};
using ASM<Add> asm = new ASM<Add>(ref MulAdd_int64);
var result=asm.Invoke(12, 13, 14);
Console.WriteLine(result);
delegate long Add(long a, long b, long c);
////////////////////////////////////////////////////////////////
public static class Win32API
{
[DllImport("kernel32.dll")]
public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpf噜阿噜dProtect);
}
public class ASM<T> : IDisposable where T: Delegate
{
private readonly byte[] data;
private IntPtr ptr;
public T Invoke;
public ASM(ref byte[] asm_code)
{
data = asm_code;
ptr = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(asm_code, 0, ptr, data.Length);
if (!Win32API.VirtualProtectEx(Process.GetCurrentProcess().Handle, ptr,(UIntPtr)data.Length, 0x40 , out uint _))
{
throw new Win32Exception();
}
Invoke = Marshal.GetDelegateForFunctionPointer<T>(ptr);
}
public void Dispose()
{
if (!Win32API.VirtualProtectEx(Process.GetCurrentProcess().Handle, ptr, (UIntPtr)data.Length, 0x04, out uint _))
{
throw new Win32Exception();
}
Marshal.FreeHGlobal(ptr);
}
} |