C#代码中插入X86汇编

时间:2021-11-18 03:39:35

这两天在看C# SIMD相关的东西, 在爆栈上面搜到一段代码, 表示很震惊, 还是得贴出来…

 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate void VectorAddDelegate(float[] C, float[] B, float[] A, int length); [DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAlloc(
IntPtr lpAddress, UIntPtr dwSize,
IntPtr flAllocationType, IntPtr flProtect); //This array of bytes has been produced from
//the SSE assembly version – it is a complete
//function that accepts four parameters (three
//vectors and length) and adds the vectors byte[] sseAssemblyBytes = {
0x8b, 0x5c, 0x24, 0x10, 0x8b, 0x74, 0x24, 0x0c, 0x8b,
0x7c, 0x24, 0x08, 0x8b, 0x4c, 0x24, 0x04, 0x31, 0xd2,
0x0f, 0x10, 0x0c, 0x97, 0x0f, 0x10, 0x04, 0x96, 0x0f,
0x58, 0xc8, 0x0f, 0x11, 0x0c, 0x91, 0x83, 0xc2, 0x04,
0x39, 0xda, 0x7f, 0xea, 0xc2, 0x10, 0x00 }; IntPtr codeBuffer = VirtualAlloc(
IntPtr.Zero, new UIntPtr((uint)sseAssemblyBytes.Length),
0x1000 | 0x2000, //MEM_COMMIT | MEM_RESERVE
0x40 //EXECUTE_READWRITE
); Marshal.Copy(sseAssemblyBytes, , codeBuffer, sseAssemblyBytes.Length); VectorAddDelegate addVectors = (VectorAddDelegate)
Marshal.GetDelegateForFunctionPointer(codeBuffer, typeof(VectorAddDelegate));
//We can now use ‘addVectors’ to add vectors!

这段代码里面的sseAssemblyBytes, 实际上是一段汇编代码, 他先把这段汇编代码拷贝到虚拟内存里面去, 然后设置这块内存可以被执行EXECUTE_READWRITE, 从而在这块内存上创建一个函数指针….

虽然这代码不能移植, 但是感觉还是有一点点屌