gpt4 book ai didi

c# - 从 ASP.NET CORE 中的字节加载程序集

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:29 25 4
gpt4 key购买 nike

我想将 roslyn 生成的程序集放入一个字节数组中(有效),然后将它从这些字节加载到另一个程序集中。它在 net framework 4.6 中工作,但似乎在 .NET CORE 中失败

这是代码。

 public class Pr2
{
public static void Main()
{
var code = File.ReadAllText(@"E:\VictoriaCMS\WebApplication4\WebApplication4\Controllers\code.cs");
var tree = SyntaxFactory.ParseSyntaxTree(code);

var compilation = CreateCompilation(tree);
var model = compilation.GetSemanticModel(tree);

ShowLocalDeclarations(tree, model);
ShowDiagnostics(compilation);
ExecuteCode(compilation);

}

private static void ShowLocalDeclarations(SyntaxTree tree, SemanticModel model)
{
var locals = tree.GetRoot()
.DescendantNodes()
.OfType<LocalDeclarationStatementSyntax>();

foreach (var node in locals)
{
var type = model.GetTypeInfo(node.Declaration.Type);
Console.WriteLine("{0} {1}", type.Type, node.Declaration);
}
}

private static void ExecuteCode(CSharpCompilation compilation)
{
using (var stream = new MemoryStream())
{
compilation.Emit(stream);

var assembly = Assembly.Load(stream.GetBuffer());

var type = assembly.GetType("Greeter");
var greeter = Activator.CreateInstance(type);
var method = type.GetMethod("SayHello");
method.Invoke(greeter, null);
}
}

private static void ShowDiagnostics(CSharpCompilation compilation)
{
var diagnostics = compilation.GetDiagnostics();
foreach (var diagnostic in diagnostics)
{
Console.WriteLine(diagnostic.ToString());
}
}

private static CSharpCompilation CreateCompilation(SyntaxTree tree)
{
var options = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary);

var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

var compilation =
CSharpCompilation.Create("test")
.WithOptions(options)
.AddSyntaxTrees(tree)
.AddReferences(reference);
return compilation;
}
}

在 .Net 核心中,出于某种原因我没有 Assembly.Load (bytes[] buffer) 过载。有人可以帮助我吗?谢谢。

  var assembly = Assembly.Load(stream.GetBuffer()); 

最佳答案

您可以使用 AssemblyLoadContext 从 .NET core 中的流加载程序集:

// requires "System.Runtime.Loader": "4.0.0",
public Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)
{
return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(peStream, pdbStream);
}

关于c# - 从 ASP.NET CORE 中的字节加载程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com