Home >Backend Development >C++ >How Can I Load and Invoke Methods from DLLs at Runtime in C#?
Detailed explanation of dynamically loading and calling DLL methods during C# runtime
In C# application development, it is often necessary to dynamically load external libraries (.DLL) to extend functions. This article will explain in detail the steps of loading a DLL at runtime and solve the common problem of being unable to call methods directly after loading.
Use Assembly.LoadFile() to load the DLL
TheAssembly.LoadFile()
method is used to load the DLL into application memory, thereby accessing the types and methods defined in the DLL. For example:
<code class="language-csharp">var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");</code>
In this example, the DLL file is loaded into memory and assigned to a variable named 'DLL'.
From LoadFile() to method call
After loading the DLL, the next step is to create an instance of the target class and call its methods. It should be noted that C# needs to know the existence of the method at compile time in order to call it directly. If the class and method are not known at compile time, another approach must be taken.
Use reflection to call methods
Reflection allows dynamic inspection and manipulation of assemblies at runtime. The steps to call a method using reflection are as follows:
GetExportedTypes()
method to get the type array exported by the DLL. Activator.CreateInstance()
method to create an instance of the target class. InvokeMember()
method to call a target method on an instance. <code class="language-csharp">foreach(Type type in DLL.GetExportedTypes()) { var c = Activator.CreateInstance(type); type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"}); }</code>
Call methods using dynamic objects (.NET 4.0 and above only)
In .NET 4.0 and above, you can use dynamic objects to dynamically call methods on instances to simplify the above process:
<code class="language-csharp">foreach(Type type in DLL.GetExportedTypes()) { dynamic c = Activator.CreateInstance(type); c.Output(@"Hello"); }</code>
Using any of the above methods, you can successfully call methods in the DLL loaded at runtime and extend the functionality of the C# application.
The above is the detailed content of How Can I Load and Invoke Methods from DLLs at Runtime in C#?. For more information, please follow other related articles on the PHP Chinese website!