Home >Backend Development >C++ >How to Safely Load, Instantiate, and Run a Class from a Dynamically Loaded Assembly?

How to Safely Load, Instantiate, and Run a Class from a Dynamically Loaded Assembly?

DDD
DDDOriginal
2025-01-21 02:23:08422browse

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.

Loading assembly

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.

Instantiate classes and call methods

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>

Uninstall assembly

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn