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

标签 c# .net

我在看这个问题: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/

相关文章:

c# - C# 中内存占用最少的最快的序列化器和反序列化器?

c# - 我可以避免这种 linq 查询冗余吗?

.net - 序列化为 XML 片段 - 而不是 XML 文档

.net - 我找不到 System.speech

c# - Silverlight - C# 和 VB.net 事件处理程序之间是否存在性能差异?

C# LINQ 自定义排序方式

c# - 使用 pdbstr 时出现 0x3 错误(源索引)

c# - WPF 绑定(bind)以控制可见性 "Numbers are not valid enumeration Values"

c# - 在 .NET 应用程序中处理音频的推荐方法?

c# - 在 .Net 中的 Excel 文档中查找最右边的单元格