我有一个用c#创建的Windows表单程序,它只是一个表单和一个按钮。我想在这里实现的是使用VirtualAlloc和委托来执行硬编码的字节数组。此硬编码字节数组与wrar.exe安装程序的字节有关。我只是想试试它是否有效。选择winrar安装程序没有特殊原因。所以在按钮点击事件中,我有这个代码:
private UInt32 MEM_COMMIT = 0x1000;
private UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private UInt32 MEM_RELEASE = 0x8000;
private delegate void Runner();
[DllImport("kernel32")]
private static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
byte[] body = new byte[1517376] { <actual bytes of the winrar installer EXE>};
private void btnExit_Click(object sender, EventArgs e)
{
try
{
IntPtr buf = VirtualAlloc(0, (UInt32)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(body, 0, (IntPtr)buf, body.Length);
Runner ptr = (Runner)Marshal.GetDelegateForFunctionPointer(buf, typeof(Runner));
ptr();
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我在这里做错了什么?它似乎与内存分配有关。我该如何解决?非常感谢提前!