Recently, it is often seen that some people ask about hosting an unmanaged instance.DLLCall problems. Calling a dynamic library is actually very simple. ManyCodeAll are implementedDLL. I mainly talk about dynamic library loading.
It is easy to implement dynamic loading for hosted dynamic libraries.
/Files/dwwwing/dlldemo.rar
Code = Assembly. LoadFile (filepath ); // Here is the path of the dynamic library.
Type TP = Ass. GetType (dlltype ); // Dlltype is the namespace + class name (namespace. Class) of the dynamic library file you need to call)
Methodinfo Method = TP. getmethod (function ); // Function to be executed
Object Ob = Activator. createinstance (TP ); // Create object
Method. Invoke (OB, Null ); // Execute the function. The last parameter is required for executing the function. If no parameter exists, it is null.
For calls to unmanaged DLL. It is a little more complicated than hosting dynamic libraries, but it is also very simple.
Use three API functions: loadlibrary, getprocaddress, and freelibrary.
Use loadlibrary to load the unmanaged DLL into the memory. Call getprocaddress to obtain the function pointer to be called. Convert an unmanaged function pointer to a delegate. Call freelibrary to release the loaded unmanaged memory ).
Code System;
Using System. Collections. Generic;
Using System. text;
Using System. runtime. interopservices;
Namespace Dlltest
{
Public Class Dllinvoke
{
[Dllimport ( " Kernel32.dll " )]
Private Static Extern Intptr loadlibrary ( String Path );
[Dllimport ( " Kernel32.dll " )]
Private Static Extern Intptr getprocaddress (intptr Lib, String Funname );
[Dllimport ( " Kernel32.dll " )]
Public Static Extern Bool Freelibrary (intptr Lib );
Private Intptr LiBr;
Public Dllinvoke ( String Path)
{
LiBr = Loadlibrary (PATH );
}
Public Delegate invoke ( String Funname, type)
{
Intptr API = Getprocaddress (LiBr, funname );
Return (Delegate) Marshal. getdelegateforfunctionpointer (API, type );
}
~ Dllinvoke ()
{
Freelibrary (LiBr ); // Release. Required
}
}
}
After completing the above function declaration, we will first set a delegate.
Code Delegate Bool Dodllfunction (); // If the function to be executed has parameters, you can declare it.
Dllinvoke = New Dllinvoke (filepath ); // Unmanaged DLL file path
Dodllfunction show = (Dodllfunction) dllinvoke. Invoke (initfunction, Typeof (Dodllfunction )); // Initfunction is the name of the function to be executed.
Show (); // Execution method. You can determine whether to pass parameters according to the definition.
How do you think it is very simple? Next, let's try it by yourself. If you have any questions, please contact me. I will give you a detailed answer.