C# load and unload dll

1. Invoker

    Any c# project

    Create a new application domain

    Create a proxy within the domain

    Unload the application domain

AppDomain ad = AppDomain.CreateDomain("DLL Unload test");
ProxyObject obj = ProxyObject)ad.CreateInstanceFromAndUnwrap(@"UnloadDll.exe", "UnloadDll.ProxyObject");
obj.LoadAssembly();
obj.Invoke("TestDll.Class1", "Test", "It's a test");
AppDomain.Unload(ad);
obj = null;

 

2. Proxy

    Implement MarshalByRefObject

    Use reflection to load dll

    Dll is unloaded when the parent application domain unloading

class ProxyObject : MarshalByRefObject
{
    Assembly assembly = null;
    public void LoadAssembly()
    {
        assembly = Assembly.LoadFile(@"TestDLL.dll");           
    }
    public bool Invoke(string fullClassName, string methodName, params Object[] args)
    {
        if(assembly == null)
            return false;
        Type tp = assembly.GetType(fullClassName);
        if (tp == null)
            return false;
        MethodInfo method = tp.GetMethod(methodName);
        if (method == null)
            return false;
        Object obj = Activator.CreateInstance(tp);
        method.Invoke(obj, args);
        return true;           
    }
}

 

posted @ 2021-05-25 19:12  xyphoenix  阅读(346)  评论(0)    收藏  举报