c# – 有人可以向我解释这个代码吗?
发布时间:2020-12-15 18:20:21 所属栏目:百科 来源:网络整理
导读:我正在看这个问题: How to implement multiplication without using multiplication operator in .NET并且实际上有很多乐趣试图想法如何在不使用*的情况下成倍增加. 但是我对这个答案感到很头疼.我不知道这段代码发生了什么. 有人可以向我解释一下吗? usin
我正在看这个问题:
How to implement multiplication without using multiplication operator in .NET并且实际上有很多乐趣试图想法如何在不使用*的情况下成倍增加.
但是我对这个答案感到很头疼.我不知道这段代码发生了什么. 有人可以向我解释一下吗? using System; using System.Runtime.InteropServices; delegate uint BinaryOp(uint a,uint b); static class Program { [DllImport("kernel32.dll",SetLastError = true)] static extern bool VirtualProtect( IntPtr address,IntPtr size,uint protect,out uint oldProtect); static void Main() { var bytes = IntPtr.Size == sizeof(int) ? //32-bit? It's slower BTW new byte[] {0x8B,0x44,0x24,0x04,0x0F,0xAF,0x08,0xC3} : new byte[] {0x0F,0xCA,0x8B,0xC1,0xC3}; var handle = GCHandle.Alloc(bytes,GCHandleType.Pinned); try { uint old; VirtualProtect(handle.AddrOfPinnedObject(),(IntPtr)bytes.Length,0x40,out old); var action = (BinaryOp)Marshal.GetDelegateForFunctionPointer( handle.AddrOfPinnedObject(),typeof(BinaryOp)); var temp = action(3,2); //6! } finally { handle.Free(); } } } 这段代码归功于Mehrdad. 解决方法
它基本上是从本机代码创建一个委托进行乘法,然后调用它.字节数组是原始指令,然后固定在内存中,设置为可执行,然后Marshal.GetDelegateForFunctionPointer创建委托本身.
条件运算符是为x86和x64使用不同的本机代码.我怀疑在ARM处理器上运行Mono时会失败,例如:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |