public static void CreateAssemblyDefinition(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); System.Collections.Generic.IReadOnlyCollection < Microsoft.CodeAnalysis.MetadataReference> _references = new[] { Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.Reflection.Binder).Assembly.Location), Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.ValueTuple <>).Assembly.Location) }; bool enableOptimisations = true; Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions options = new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary, optimizationLevel: enableOptimisations ? Microsoft.CodeAnalysis.OptimizationLevel.Release : Microsoft.CodeAnalysis.OptimizationLevel.Debug, allowUnsafe: true ); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName: "InMemoryAssembly", options: options) .AddReferences(_references) .AddSyntaxTrees(syntaxTree); System.IO.MemoryStream stream = new System.IO.MemoryStream(); Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream); if (emitResult.Success) { stream.Seek(0, System.IO.SeekOrigin.Begin); // System.Reflection.Metadata.AssemblyDefinition assembly = System.Reflection.Metadata.AssemblyDefinition.ReadAssembly(stream); } }
} // End Sub Test // emit the compilation result into a byte array. // throw an exception with corresponding message // if there are errors private static byte[] EmitToArray ( this Microsoft.CodeAnalysis.Compilation compilation ) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { // emit result into a stream Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream); if (!emitResult.Success) { // if not successful, throw an exception Microsoft.CodeAnalysis.Diagnostic firstError = emitResult .Diagnostics .FirstOrDefault ( diagnostic => diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error ); throw new System.Exception(firstError?.GetMessage()); } // get the byte array from a stream return stream.ToArray(); } // End Using stream } // End Function EmitToArray
private static void CreateCsCompilation(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName, new[] { syntaxTree }, references, new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary) ); // byte[] compilationResult = compilation.EmitToArray(); // System.Reflection.Assembly.Load(compilationResult); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // _compilation = compilation; }
} // End Sub CheckCompilationResult private static void CreateCompilation2(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, new[] { syntaxTree }, references, co ); // WTF !!! // byte[] compilationResult = compilation.EmitToArray(); // Load the resulting assembly into the domain. // System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(compilationResult); /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } }
private static void CreateCompilationMultiFile(string[] filenames) { string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.SyntaxTree[] syntaxTrees = new Microsoft.CodeAnalysis.SyntaxTree[filenames.Length]; Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions op = null; for (int i = 0; i < filenames.Length; ++i) { string fileContent = System.IO.File.ReadAllText(filenames[i], System.Text.Encoding.UTF8); syntaxTrees[i] = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText( fileContent , op , filenames[i] , System.Text.Encoding.UTF8 ); } Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, syntaxTrees, references, co ); // byte[] compilationResult = compilation.EmitToArray(); using (System.IO.MemoryStream dllStream = new System.IO.MemoryStream()) { using (System.IO.MemoryStream pdbStream = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(dllStream, pdbStream); if (!emitResult.Success) { CheckCompilationResult(emitResult); } // End if (!emitResult.Success) } // End Using pdbStream } // End Using dllStream /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // End Using ms }