我在看这个问题: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。
最佳答案
它基本上是从 native 代码创建一个用于乘法的委托(delegate),然后调用它。字节数组是原始指令,然后固定在内存中,设置为可执行,然后 Marshal.GetDelegateForFunctionPointer
创建委托(delegate)本身。
条件运算符是针对 x86 和 x64 使用不同的 native 代码。我怀疑这会在 ARM 处理器上运行 Mono 时失败,例如 :)
关于c# - 有人可以向我解释这段代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5916690/