有人可以向我解释这段代码吗?

问题描述:

我在看这个问题: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, 0x44, 0x24, 0x08, 0xC3} 
     : new byte[] {0x0F, 0xAF, 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时会失败,例如:)

此代码包含CPU指令的二进制文件。它找到二进制的地址并执行它。除了作为一个消极的例子或笑话之外,这很糟糕。

它是实现乘法的汇编语言代码。 VirtualProtect的调用是为了使代码执行在本来不可执行的数据段中。

+0

实际上是本机机器码,而不是汇编语言。 – 2011-05-07 11:51:11