从内存中加载组件组件、加载、内存

2023-09-06 08:20:17 作者:第十九个梦。

我移植其中,类在运行时从内存中加载和执行的Java应用程序(一个字节数组)。我想实现在C#同样的事情,但我有问题( System.IO.FileNotFoundException 例外)试图加载从字节数组组件(使用时 AppDomain.Load 法)。

I am porting a Java application where classes are loaded and "executed" at runtime from memory (a byte array). I am trying to achieve the same thing in C#, but I am having problems (System.IO.FileNotFoundException exceptions) when trying to load assemblies from byte arrays (using the AppDomain.Load method).

static void Main(string[] args)
{
    var domain = AppDomain.CreateDomain("foo");

    domain.AssemblyResolve += new ResolveEventHandler(domain_AssemblyResolve);

    var assembly = domain.Load("MyAssembly");
}
static Assembly  domain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    // ...
    return Assembly.ReflectionOnlyLoad(File.ReadAllBytes(@"C:\MyAssembly.exe"));
}

有没有办法来加载它们的不需要坚持这个字节数组到文件系统?

Is there a way to load them without the need to persist this byte array into the file system?

简化的想法,我们希望有执行和变更(更新)code动态的能力。我们使用单独的应用程序域装载/卸载组件。

Simplifying the idea, we want to have the ability to execute and change (update) code dynamically. We use separate application domains to "load/unload" assemblies.

推荐答案

我只是想这code:

static void Main(string[] args)
        {

            var h = File.ReadAllBytes(@"C:\MyAssembly.exe");

            var g = Assembly.Load(h);            
        }

和它工作得很好 - 我没有得到任何的异常。你100%的确保目标组件的存在?

and it worked fine - I did not get any exceptions. Are you 100% sure that the target assembly exists?