从MemoryStream加载C#程序集:错误的IL格式。如何正确加载完全内存中的程序集?

时间:2018-12-11 09:48:46

标签: c# .net-core dllimport asp.net-core-2.1

使用 .NET Core 2.1 Microsoft.CodeAnalysis.CSharp.Scripting 2.10.0 动态地编译程序集并将其保留为内存中。然后尝试通过AssemblyLoadContext获取

来加载此程序集
  

错误的IL格式

如何正确加载完整的内存程序集? 发生此异常的原因是什么? 我想为内存中的程序集指定一些元数据吗? 错误的IL格式还有什么最常见的情况?

下面的代码示例产生异常:

using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace ConsoleApp2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (Stream stream = new MemoryStream())
            {

                var compilation = CSharpCompilation.Create("a")
                    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                    .AddReferences(
                        MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location))
                    .AddSyntaxTrees(CSharpSyntaxTree.ParseText(
                    @"

public static class C
{
    public static int M(int a, int b)
    {
        return a+b;
    }
}

                    "));

                var results = compilation.Emit(stream);
                //results.Success is true here
                var context = AssemblyLoadContext.Default;
                Assembly a = context.LoadFromStream(stream);//<--Exception here.
            }
        }
    }
}

运行时异常详细信息:

System.BadImageFormatException
  HResult=0x8007000B
  Message=Bad IL format.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, Int32 iAssemblyArrayLen, IntPtr ptrSymbols, Int32 iSymbolArrayLen, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromStream(Stream assembly, Stream assemblySymbols)
   at ConsoleApp2.Program.<Main>d__0.MoveNext() in C:\repos\sketches\ConsoleApp2\Program.cs:line 37
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ConsoleApp2.Program.<Main>(String[] args)

0 个答案:

没有答案