Last active
June 21, 2024 21:08
-
-
Save Dump-GUY/2d1a16e7ee07c059c216a389d89b07b8 to your computer and use it in GitHub Desktop.
Example of DynamicCompiler - dynamically compile C# code -> but it actually spawns csc.exe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.CodeDom.Compiler; | |
using Microsoft.CSharp; | |
using System.Linq; | |
namespace DynamicCompiler | |
{ | |
internal class Program | |
{ | |
public static void DynamicRun(string codes, string clazz, string method, string[] args) | |
{ | |
CompilerResults compilerResults = new CSharpCodeProvider().CreateCompiler().CompileAssemblyFromSource(new CompilerParameters | |
{ | |
ReferencedAssemblies = { "System.dll" }, | |
GenerateExecutable = false, | |
GenerateInMemory = true | |
}, codes); | |
if (compilerResults.Errors.HasErrors) | |
{ | |
string.Join(Environment.NewLine, from CompilerError err in compilerResults.Errors select err.ErrorText); | |
Console.WriteLine("error"); | |
} | |
object obj = compilerResults.CompiledAssembly.CreateInstance(clazz); | |
obj.GetType().GetMethod(method).Invoke(obj, args); | |
} | |
static void Main() | |
{ | |
string srcCode = "using System;namespace HelloWorld{public class Program{public static void Main(){Console.WriteLine(\"Hello World !!!\");}}}"; | |
string myClass = "HelloWorld.Program"; | |
string myMethod = "Main"; | |
string[] args = Array.Empty<string>(); | |
DynamicRun(srcCode, myClass, myMethod, args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment