Home >Backend Development >C++ >How to Safely Load, Instantiate, and Run a Class from a Dynamically Loaded Assembly?
Best Practice: Dynamically load assemblies, instantiate classes and run methods
In dynamic programming, it is often necessary to load assemblies, instantiate classes and call their methods. This article introduces an efficient and safe implementation method.
Dynamic loading of assemblies can be done using the Assembly.LoadFile
method, which receives the path to the assembly file as a parameter. After an assembly is loaded, you can get its types, methods, and other details.
There are many ways to instantiate a class and call its methods. However, for dynamically loaded assemblies, there are advantages to using reflection. Reflection allows you to access and call members of a type at runtime.
Traditional method:
The following code demonstrates the traditional method of casting an instantiated object to the required interface:
<code class="language-csharp">Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll"); IRunnable r = assembly.CreateInstance("TestRunner") as IRunnable; if (r == null) throw new Exception("broke"); r.Run();</code>
Recommended method: Use AppDomain:
A safer and more flexible approach is to load the assembly into its own AppDomain first. This allows for better isolation and control. Replace the previous code with the following code:
<code class="language-csharp">var domain = AppDomain.CreateDomain("NewDomainName"); var type = typeof(IRunnable); var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\dyn.dll", type.Name) as IRunnable; if (runnable == null) throw new Exception("broke"); runnable.Run();</code>
If an assembly is no longer needed, it can be uninstalled using the AppDomain.Unload
method. This helps with resource management and avoids memory leaks.
In summary, using AppDomain to load and unload assemblies is the recommended approach as it provides better flexibility, security, and enhanced isolation.
The above is the detailed content of How to Safely Load, Instantiate, and Run a Class from a Dynamically Loaded Assembly?. For more information, please follow other related articles on the PHP Chinese website!