使用 mono_assemble_load_from 加载程序集时如何获取程序集?

问题描述 投票:0回答:1

我使用 Mono 方法将程序集加载到应用程序中。问题是,当我加载程序集时,我只得到

IntPtr
,但我需要
System.Reflection.Assembly
。如何使用
IntPtr
获得它?

我导入和使用的方法:

public static class MonoCalls {
    [DllImport("__Internal", EntryPoint = "mono_image_open_from_data")]
    public static extern IntPtr MonoImageOpenFromData(IntPtr dataHandle, int dataLenght, bool shouldCopy, IntPtr status);

    [DllImport("__Internal", EntryPoint = "mono_assembly_load_from")]
    public static extern IntPtr MonoAssemblyLoadFrom(IntPtr imageHandle, string name, IntPtr status);
}

用于将程序集加载到内存中的类(输入是字节数组形式的程序集):

public class Mono {
    IntPtr Image;
    IntPtr Assembly;
    public IntPtr Activate(byte[] Bytes) {
        unsafe {
            fixed (byte* Pointer = Bytes) {
                Image = MonoCalls.MonoImageOpenFromData((IntPtr)Pointer, Bytes.Length, true, IntPtr.Zero);
                Assembly = MonoCalls.MonoAssemblyLoadFrom(Image, string.Empty, IntPtr.Zero);
                return Assembly;
            }
        }
    }
}

主要代码:

...

Mono Mono = new();
byte[] Assembly_Bytes = ...; // Assembly
IntPtr Pointer = Mono.Activate(Assembly_Bytes);
string MyAssemblyName = "MyAssembly";

Assembly FoundAssembly;
foreach (Assembly Assembly in AppDomain.CurrentDomain.GetAssemblies()) {
    if (Assembly.GetName().Name.Equals(MyAssemblyName)) {
        FoundAssembly = Assembly; // Got it (or an assembly with similar name)
        return;
    }
}

Type[] Types = FoundAssembly.GetTypes(); // Main purpose of this part of code
...

有没有像

GetAssemblyByPtr(IntPtr)
这样返回
System.Reflection.Assembly
的方法?

*简单

Assembly.Load()
不适合我的情况。

c# mono dllimport .net-4.8
1个回答
0
投票

在加载程序集之前,如果我收到程序集,我会绑定到程序集加载事件。加载后,事件解除绑定。

主要代码:

...
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
...
// Loading assemblies
// It's supposed to load only the assemblies I need at the moment.
...
AppDomain.CurrentDomain.AssemblyLoad -= CurrentDomain_AssemblyLoad;
...
private void CurrentDomain_AssemblyLoad(object Sender, AssemblyLoadEventArgs AssemblyLoadEventArgs) {
    Console.WriteLine("CurrentDomain_AssemblyLoad");
    Assembly MyAssembly = AssemblyLoadEventArgs.LoadedAssembly;
    // Got loaded assembly (or assemblies)
}
© www.soinside.com 2019 - 2024. All rights reserved.