How to invoke dynamic link library Dll_ practical tips in asp.net/c#

Source: Internet
Author: User
Tags emit modifier reflection win32

The

dynamic link library (also known as a DLL, abbreviated as the dynamic link library) is one of the most important components of Microsoft Windows, opening Windows system folders. You will find that there are many DLL files in the folder, and Windows is implementing some of the major system functions as DLL modules. A
dynamic-link library cannot be executed directly or receive messages, it is just a separate file that contains functions that can be invoked by a program or other DLL to do something (method). Note: C # is commonly referred to as "methods", but these functions are not part of the execution program itself, but are loaded on demand according to the needs of the process, at which point it works. The
DLL is loaded into the virtual space of the process only when the application requires it. becomes part of the calling process, at which point the DLL can only be accessed by the thread of the process, and its handle may be used by the calling process, and the handle of the calling process can also be used by the DLL. In memory, a DLL has only one instance, and its programming is not related to the specific programming language and compiler, so you can implement mixed language programming through a DLL. Any object (including variables) created by code in a DLL function is owned by the thread or process that calls it.
The following lists some of the benefits that are provided when your program uses DLLs:

1) uses fewer resources
When multiple programs use the same function library, DLLs can reduce the amount of duplication of code that is loaded in disk and physical memory. This can affect not only the programs that are running in the foreground, but also other programs that run on the Windows operating system.
2) to promote modular architecture
DLLs help facilitate the development of modular programs. This can help you develop large programs that require multiple language versions or programs that require a modular architecture. An example of a modular program is an accounting program that has multiple modules that can be loaded dynamically at run time.
3 simplifies deployment and installation
when a function in a DLL needs to be updated or repaired, the deployment and installation DLL does not require you to re-establish the link between the program and the DLL. In addition, if multiple programs use the same DLL, multiple programs will benefit from that update or fix. This problem may occur more frequently when you use a third-party DLL that is regularly updated or repaired.
Each programming language invokes a DLL in a different way, where only the method of calling a DLL in C # is described. First, you need to understand what is managed and what is unmanaged. It is generally assumed that unmanaged code is primarily a Dll,activex component based on the win 32 platform, and managed code is developed based on the. NET platform. If you want to learn more about the relationships and differences between managed and unmanaged, and how they operate, please find the information yourself, this document is not discussed here.

(i)  , calling the unmanaged function generic method
in a DLL first, you should declare an external method in the C # language source, in the basic form:
[DllImport (" DLL file ")]
modifier extern Returns the variable type method name (parameter list)
Where:
DLL file: Contains a library file that defines an external method.
Modifier: An access modifier that can be used when declaring a method other than abstract.
Return Variable type: You need to call the return variable type of the method in the DLL file.
Method Name: You need to invoke the name of the method in the DLL file.
argument list: You need to call the list of methods in the DLL file.
Note: You need to use the System.Runtime.InteropServices namespace in your program declaration. The
          dllimport can only be placed on a method declaration.

The DLL file must reside in the program's current directory or in a system-defined query path (that is, the path set by path in the system environment variable).
Returns the variable type, method name, and argument list must be consistent with the definition in the DLL file.
To use a different function name, you can use the EntryPoint property setting, such as:
[DllImport ("user32.dll", entrypoint= "MessageBoxA")]
static extern int MsgBox (int hWnd, string msg, string caption, int type);
Other optional DllImportAttribute properties: Ah
CharSet indicates the character set used in the entry point, such as: Charset=charset.ansi;
SetLastError indicates whether the method retains the Win32 "previous error", such as: setlasterror=true;
ExactSpelling Indicates whether entrypoint must exactly match the spelling of the indicated entry point, such as: Exactspelling=false;
PreserveSig indicates whether the signature of the method should be retained or converted, such as: preservesig=true;
CallingConvention indicates the calling convention for the entry point, such as: CALLINGCONVENTION=CALLINGCONVENTION.WINAPI;
In addition, for data marshaling and marshaling numbers and logical scalars, see some other articles [2].

C # Example:

1. Start Vs.net, create a new project with the project name "Tzb" and the template is "Windows application."
2. In the Windows forms item of the Toolbox, double-click the button item to add a button to the Form1 form.
3. Change the properties of the button: name is "B1", Text is "Invoke DLL pop-up balloon with DllImport", and adjust the button B1 to the appropriate size, move to the appropriate position.
4. In Class View, double-click "Form1" to open "Form1." CS Code view, enter "using System.Runtime.InteropServices;" Above "namespace Tzb" to import the namespace.
5. In "Form1." cs[design] In the view, double-click the button B1 and use the keyword static and extern declaration method "MsgBox" above the "B1_click" method to attach the DllImport property to the method, where we will use "user32." DLL "MessageBoxA" function, the specific code is as follows:

[DllImport ("user32.dll", entrypoint= "MessageBoxA")]
static extern int MsgBox (int hWnd, string msg, string caption, int type);

The following code is then added to the "B1_click" method body to invoke the method "MsgBox":
MsgBox (0, "That's the pop-up box with the DllImport call DLL!") "," the Challenge Cup, 0x30);
6. Press "F5" to run the program, and click the button B1, it will pop up the following prompt box:

7. The code is as follows:

 using System; using System.Collections.Generic; using System.ComponentModel; using Sy Stem.
Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;

Using System.Runtime.InteropServices; namespace WindowsFormsApplication1 {public partial class Form1:form {[DllImport ("user32.dll", EntryPoint = "M
    Essageboxa ")] static extern int MsgBox2 (int hWnd, string msg, string caption, int type);
    Public Form1 () {InitializeComponent (); private void Form1_Load (object sender, EventArgs e) {} private void Button1_Click (object sender , EventArgs e) {MsgBox2 (0, "This is the Prompt box that pops up with the DllImport call DLL!")
    "," the Challenge Cup, 0x30); } private void Button2_Click (object sender, EventArgs e) {MsgBox2 (0, "This is the Prompt box that pops up with the DllImport call DLL Oh 222222 F!

    "," 222222 ", 0x30); }
  }
}

(ii) dynamic loading, calling unmanaged functions in DLLs
it already shows how to call an unmanaged function in a DLL with DllImport, but this is a global function, and if the unmanaged function in the DLL has a static variable s, the static variable s is automatically added 1 each time the function is called. As a result, you can't get the results you want when you need to count back. The following examples illustrate:
1. dll Creation
1), start Visual C + + 6.0;
2), a new "Win32 Dynamic-link Library" project, the project name is "Count";
3), select "A Simple DLL Project" in the "Dll kind" selection interface;
4), open Count.cpp, add the following code:

Export functions, using the "_stdcall" standard to invoke
extern "C" _declspec (dllexport) int _stdcall count (int init);
int _stdcall count (int init)
{//count function, initializes the static shape variable s with parameter init, and returns the value static int s=init After the S is added 1
;
s++;
return S;
}

5), according to "F7" to compile, get Count.dll (in the Engineering directory in the Debug folder).
2. Call the Count function in the DLL with DllImport
1, open the item "TZB" and add a button to the "Form1" form.
2), change the properties of the button: name is "B2", Text is "call the Count function in the DLL with DllImport", and push the button B1 to the appropriate size and move to the appropriate position.
3), open "Form1." CS Code view, using the keyword static and extern declaration method "Count" and having it implemented with the count of the exported function from Count.dll, the code is as follows:

[DllImport ("Count.dll")]
static extern int count (int init);

4), in "Form1." cs[design] View, double-click the button B2 to add the following code in the B2_click method body:
MessageBox.Show ("Call the Count function in the DLL with DllImport, n the argument passed in is 0, and the result is:" +count (0). ToString (), "Challenge Cup");
MessageBox.Show ("Call the Count function in the DLL with DllImport, n the argument passed in is 10, and the result is:" +count (10). ToString () + "N results are not 11 Oh!!! "," the Challenge Cup ");
MessageBox.Show ("The results show that: N using DllImport to call unmanaged n functions in a DLL is a global, static function!!! "," the Challenge Cup ");
5, the Count.dll copy to the project "Tzb" Bindebug folder, press "F5" Run the program, and click on the button B2, it will pop up the following three balloon:

The

1th box shows the result of calling count (0), and the 2nd box shows the result of calling Count (10), which proves that "calling unmanaged functions in a DLL with DllImport is a global, static function." So, sometimes it doesn't work out for us, so we need to use the method described below: C # dynamically calls functions in DLLs.
3. c# functions in dynamically calling DLLs
Because DllImport is not used in C # as dynamic Load/unload assembly, So you can only use API functions. In Kernel32.dll, functions related to dynamic library calls include the following:

①loadlibrary (or MFC's AfxLoadLibrary) to load the dynamic library.
②getprocaddress, gets the function to introduce, converts the symbol name or identification number to the internal address of the DLL.
③freelibrary (or MFC's AfxFreeLibrary) to release the dynamic link library.
Their prototypes are:
Hmodule LoadLibrary (LPCTSTR lpfilename);
Farproc GetProcAddress (hmodule hmodule, lpcwstr lpprocname);
BOOL FreeLibrary (hmodule hmodule);
Now we can use the IntPtr hmodule=loadlibrary ("Count.dll") to get the handle to the DLL, with IntPtr farproc=getprocaddress (hmodule, "_count@4") To obtain the entry address of the function.
However, how do you call this function after you know the entry address of the function? Because there is no function pointer in C #, there is no way to invoke functions like C + +, so we have to use other methods. After research, we find that we can achieve our goal by combining the classes and functions in System.Reflection.Emit and System.Reflection.Assembly. We can write a class in order to be easy to use later and to implement the code reuse.
1), writing of the DLD class:
1.  Open the project "Tzb", open Class View, right-click "Tzb", select "Add"--> "Class", and the class name is set to "DLD". The beginning letter of each word of the dynamic loading DLL.
2.  Add the required namespaces and declare the parameter passing method enumeration:

Using System.Runtime.InteropServices; Use System.Reflection for this namespace using the DllImport;//
Use the Assembly class to require this namespace using
System.Reflection.Emit;//Use Ilge Nerator requires this namespace

Add the following code declaration parameter delivery method enumeration above "public class DLD":

<summary>
///Parameter Passing method enumeration, byvalue representing value passing, ByRef representing address delivery
///</summary> public
enum Modepass
{
byvalue = 0x0001,
ByRef = 0x0002
}

3. Declare LoadLibrary, GetProcAddress, FreeLibrary and private variables hmodule and Farproc:

<summary>///prototype is: Hmodule LoadLibrary (LPCTSTR lpfilename); </summary>///<param name= "lpfilename" >dll filename </param>///<returns> function library module handle </returns
> [DllImport ("kernel32.dll")] static extern IntPtr LoadLibrary (string lpfilename);
<summary>///prototype is: Farproc GetProcAddress (hmodule hmodule, lpcwstr lpprocname); </summary>///<param name= "Hmodule" > containing the handle of a function library module that calls functions </param>///<param name= "Lpprocname" > Calling function name </param>///<returns> function Pointer </returns> [DllImport ("kernel32.dll")] static extern IntPtr Ge
Tprocaddress (IntPtr hmodule, string lpprocname);
<summary>///prototype is: BOOL FreeLibrary (hmodule hmodule); </summary>///<param name= "hmodule" > The handle of the function library module that needs to be freed </param>///<returns> whether the specified dll 

4. Add the Loaddll method, and in order to invoke the convenience, overload this method:

<summary>
///Loader Dll
///</summary>
///<param name= "lpfilename" >dll file name </param > Public
void Loaddll (string lpfilename)
{
hmodule=loadlibrary (lpfilename);
if (Hmodule==intptr.zero)
throw (new Exception (not found: "+lpfilename+"));
     If you already have a handle to a loaded DLL, you can use the second version of the Loaddll method: public
void Loaddll (IntPtr hmodule)
{
if (Hmodule==intptr.zero)
throw ("The handle of the passed in Function library module hmodule is null.");
Hmodule=hmodule;
}

5. Add the Loadfun method, and in order to invoke the convenience, also overloaded the method, the specific code of the method and comments as follows:

///<summary>///get function pointer///</summary>///<param name= "Lpprocname" ; The name of the calling function </param> public void Loadfun (string lpprocname) {//If the handle of the function library module is empty, throws an exception if (Hmodule==intptr.zero) throw (new E
Xception ("The handle of the function library module is empty, make sure you have Loaddll operation!");
Get function pointer farproc = GetProcAddress (hmodule,lpprocname);
If the function pointer throws an exception if (Farproc==intptr.zero) throw (new Exception ("Not Found:" +lpprocname+ "The entry point of this function)"); <summary>///Get function pointer///</summary>///<param name= "lpFileName" > contains DLL file name to call function </param>// /<param name= "Lpprocname" > Calling function name </param> public void Loadfun (string lpfilename,string lpprocname) {//Get Letter
The handle hmodule=loadlibrary (lpFileName) of the number library module;
If the function library module has a null handle, throws an exception if (Hmodule==intptr.zero) throw (new Exception ("Not Found: +lpfilename+"));
Get function pointer farproc = GetProcAddress (hmodule,lpprocname); If the function pointer throws an exception if (Farproc==intptr.zero) throw ("Not Found:" +lpprocname+ "The entry point of this function)" (New Exception);} 

6. Add Unloaddll and Invoke methods, the Invoke method is also overloaded:

<summary>
///Uninstall Dll
///</summary> public
void Unloaddll ()
{
FreeLibrary ( hmodule);
Hmodule=intptr.zero;
Farproc=intptr.zero;
}

The above is asp.net call dynamic link Library DLL method, hope for everyone's learning help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.