c# – 是否有可能完全在托管的.NET语言中编写一个JIT编译器(到本地代码)

我想写一个JIT编译器的想法,只是想知道是否甚至理论上可能写在托管代码的整个事情。特别是,一旦你将汇编器生成为字节数组,你如何跳转到它开始执行?
并且为了完全证明概念这里是一个完全能力的翻译Rasmus的方法到JIT到F#

open System
open System.Runtime.InteropServices

type AllocationType =
    | COMMIT=0x1000u

type MemoryProtection =
    | EXECUTE_READWRITE=0x40u

type FreeType =
    | DECOMMIT = 0x4000u

[<DllImport("kernel32.dll", SetLastError=true)>]
extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect);

[<DllImport("kernel32.dll", SetLastError=true)>]
extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, FreeType freeType);

let JITcode: byte[] = [|0x55uy;0x8Buy;0xECuy;0x8Buy;0x45uy;0x08uy;0xD1uy;0xC8uy;0x5Duy;0xC3uy|]

[<UnmanagedFunctionPointer(CallingConvention.Cdecl)>] 
type Ret1ArgDelegate = delegate of (uint32) -> uint32

[<EntryPointAttribute>]
let main (args: string[]) =
    let executableMemory = VirtualAlloc(IntPtr.Zero, UIntPtr(uint32(JITcode.Length)), AllocationType.COMMIT, MemoryProtection.EXECUTE_READWRITE)
    Marshal.Copy(JITcode, 0, executableMemory, JITcode.Length)
    let jitedFun = Marshal.GetDelegateForFunctionPointer(executableMemory, typeof<Ret1ArgDelegate>) :?> Ret1ArgDelegate
    let mutable test = 0xFFFFFFFCu
    printfn "Value before: %X" test
    test <- jitedFun.Invoke test
    printfn "Value after: %X" test
    VirtualFree(executableMemory, UIntPtr.Zero, FreeType.DECOMMIT) |> ignore
    0

愉快地执行屈服

Value before: FFFFFFFC
Value after: 7FFFFFFE
http://stackoverflow.com/questions/9557293/is-it-possible-to-write-a-jit-compiler-to-native-code-entirely-in-a-managed-n

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 是否有可能完全在托管的.NET语言中编写一个JIT编译器(到本地代码)