简体   繁体   中英

Compile .IL at runtime C#

I have no idea how to do compile IL code at runtime. I use .NET core 3.1 and I can generate a string which contains

.assembly extern mscorlib {}
.assembly Hello {}
.module Hello.exe

.class Hello.Program
extends [mscorlib]System.Object
{
    .method static void Main(string[] args)
    cil managed
    {
        .entrypoint

        ldstr "H"
        call void[mscorlib]
            System.Console::
        Write(string)

        ldstr "i"
        call void[mscorlib]
            System.Console::
        Write(string)

        ret
    }
}

But how do I then compile the file? I want to do it at runtime. (ignore the bad IL code)

So, i found out how to do it. I copied the ilasm.exe and fusion.dll from my .net framework folder and then i saved the string to a file and then i used ProcessInfo to run ilasm file . That then outputted the exe i wanted.

For anybody who is wondering, ilasm.exe is located in C:\Windows\Microsoft.NET\Framework\Verison if you replace verison with the framework verison, for example v4.0.30319.

Thanks to anybody who tried to help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM