DLL learning-reprint

Source: Internet
Author: User
Tags textout types of functions

When learning DLL, it is difficult to understand the essence of DLL without the help of examples. Now I want to introduce an example:
1. Add a function in the DLL: Fun (double A, double B)
// If I am too lazy to type, I Will plagiarize others (many people, thank you:
//////////////////////////////////////// //////////////////////////
1. Static DLL loading method:
Function Definition and usage:

Step 1:

Run Appwizard and define the project name mydll. Select MFC Appwizard (DLL) instead of MFC appwizards (exe ).

Step 2:

In this example, only one Appwizard screen appears.
Show DLL (MFC extension DLL (using shared mfc dll), click Finish to generate the project.

Step 3:

Click new in file, select C/C ++ header file, enter DLL in file name, and click OK to create DLL. h.
Enter extern "C" _ declspec (dllexport) int fun (INT X1, int X2, int X3); and save.

Step 4:

Click new in file, select C ++ source file, enter DLL in file name, and click OK to create DLL. cpp. Input

# Include "stdafx. H"
# Include "DLL. H"
Extern "C" _ declspec (dllexport) int fun (INT X1, int X2, int X3)
{
Return X1 + X2 + X3;
}

Compile and generate mydll. dll and mydll. Lib.

Step 5:

Select "new" in "add to Project" in the project, regenerate a project, and select "MFC appwizards (exe)". The project name
For mydlltest, select single document and click Finish to generate a new project. Select menu
Project set as active project mydlltest, set mydlltest as the current active project.

Step 6:

Copy... /Mydll/debug/mydll. DLL to ../mydlltest/debug/, copy... /Mydll/debug/mydll. lib... /Mydlltest/directory.

Step 7:

Add it under # endif in mydlltestview. cpp

Extern "C" _ declspec (dllimport) int fun (INT X1, int X2, int X3 );

Add the following code to void cmydlltestview: ondraw (CDC * PDC:

Void cmydlltestview: ondraw (CDC * PDC)
{
Cmydlltestdoc * pdoc = getdocument ();
Assert_valid (pdoc );
// Todo: Add draw code for native data here
Int x = fun (1, 2, 3 );
Cstring STR;
Str. Format ("% d", X );
PDC-> textout (10, 10, STR );
}

Step 8:

Right-click mydlltest files in workspace, select add files to project, and add mydll. lib to project.
Now, we have finished our work. Run it!
//////////////////////////////////////// ///////////////////
2. Dynamic DLL loading:

Start from Step 6:

Add the following code to void cmydlltestview: ondraw (CDC * PDC:
Void cmydlltestview: ondraw (CDC * PDC)
{
Cmydlltestdoc * pdoc = getdocument ();
Assert_valid (pdoc );
// Todo: Add draw code for native data here
Int X;
Typedef int (* padd) (INT X1, int X2, int X3 );
Hinstance hdll;
Padd add;
Hdll = loadlibrary ("mydll. dll ");
Add = (padd) getprocaddress (hdll, "fun ");
X = add (2, 6, 5 );
Cstring STR;
Str. Format ("% d", X );
PDC-> textout (10, 10, STR );

}

Right-click mydlltest files in workspace, select add files to project, and add mydll. lib to project.
Now, we have finished our work. Run it!

Reference announcement address: http://blog.csdn.net/sgnah/services/trackbacks/330837.aspx

Exploring the programming principles of dynamic link library (DLL) under Win32

Topic: DLL is the most important component of windows. Many new features and features in windows are implemented through DLL.
Therefore, it is very important to master and apply it.
The dynamic link library can be used not only as a running module, including function code, but also contains any data other than the program.
Or resources (bitmap, icon, and so on ). The Dynamic Link Library provides functions or resources for applications.
A dll is a disk file (usually with a dll extension) that consists of global data, service functions, and resources,
The system is loaded into the virtual space of the Process during running and becomes part of the calling process. When running, only when
The system will load these DLL modules to the memory space only when the program does call these DLL modules. Every process repeat
Write/read global variables. To share memory with other processes, you must use the memory ing file or sound
A shared data segment. The stack memory required by the DLL module is allocated from the stack of the running process.
The DLL file contains an export function table. These export functions are associated with the external world by their symbolic names and integers called identifiers.

Import and export functions:
In the DLL code, the export function must be explicitly declared as follows:
_ Declspec (dllexport) int myfunction (int n );
However, you can also list the export functions in the module definition (DEF) file, but this will often cause more trouble. In terms of applications
The following example explicitly declares the corresponding input function:
_ Declspec (dllimport) int myfuncition (int n); (this is an implicit link DLL)
Only the import and export declarations do not allow function calls within the application to be linked to the corresponding DLL file. The project of the application must be
The link Program specifies the required input Library (LIB file ). In addition, the application must contain at least one call to the DLL function.
Implicit link and explicit link DLL

Explicit: typedef double (sqrtproc) (double );

Hinstance; // you can specify global variables to store DLL handles.
Sqrtproc * pfunction; the second variable showme is the pointer to the DLL function in the library.
Verify (hinstance =: loadlibrary ("C: // winnt // system32 // mydll. dll "));
Verify (pfunction = (sqrtproc *): getprocaddress (hinstance, "squareroot "));
Double D = (* pfunction) (81.0); // call this DLL Function
Implicit: When a programmer compiles an application using a static link, the calling function in the application is equivalent to the exported symbol in the Lib file.
Match, these symbols or identifiers enter the generated EXE file.
The difference between implicit link and explicit link DLL:
In the implicit link mode, all DLL files called by the application will be loaded into the memory when the application EXE file is loaded;
If explicit links are used, the programmer can determine when or not to load the DLL file.

 

Dllmain function:
This function is called when Windows loads the DLL module. The system first calls the constructor of the global object and then calls the global function dllmain.
The dllmain function is called not only when the DLL link is loaded to the process, but also when the DLL module is separated from the process (and other times.
Each DLL module in a process is identified by a globally unique 32-byte hinstance handle. The process itself has an hinstance handle. Institute
These module handles are only valid within a specific process. They represent the starting address of the DLL or EXE module in the process virtual space.
Find the dll path:
Windows will follow the search order below to locate the DLL:
1. directory containing the EXE file,
2. current working directory of the process,
3. Windows System directory,
4. Windows Directory,
5. A series of directories listed in the PATH environment variable.

Key points:

1. The saved name of the DLL file is the same as that of the project (also the name after library in the. Def file ).
Modify the file name of the. dll file.

Two types of functions are defined in dll:
Exportfunction: can be called by other modules.
Internal function (internalfunction): can only be used within the DLL

The MFC-Based DLL does not apply to the DLL used to prepare and read binary files (it is not easy to transplant and cannot correctly read binary files shared with DOS applications)
API-Based DLL can correctly read binary files created in the DOS environment.
Pure standard function dll can be used on many platforms! (Most portable)
To enable other languages: unless you absolutely need to use C ++ encoding, I recommend using C to write DLL.
DLL type under VC:
Non-mfc dll: refers to the DLL directly written in C language without the MFC class library structure. Its output function 1
Is a standard C interface, and can be called by applications not written in MFC or MFC. Ll,

Regular DLL: similar to the following extension DLLs, it is written in the MFC class library. Obviously
In the source file, there is a class that inherits cwinapp. It can be subdivided into static connection to MFC and dynamic connection to MFC.
. However, the dynamic connection library for static connection to MFC is only supported by VC professional and Enterprise Edition.

Extension DLL: Used to reuse the classes inherited from MFC.
Type Dynamic Connection Library, which can be used to output a class inherited from MFC. Extension DLL uses
The dynamic connection version is created and called only by applications written in the MFC class library.
It is used to reuse the classes inherited from MFC. That is to say, this type of dynamic connection library can be used
To output a class inherited from MFC. The function output by this tool can only be used by the MFC and dynamically linked to the MFC application.
Program usage. You can inherit the classes you want from MFC that are more suitable for your use and provide them to your applications.
You can also provide the object pointer of the MFC or MFC inheritance class to your application at will. Using MFC for extension DLL
The State connection version is created, and it is called only by applications written in the MFC class library. Extension DLLs and
Regular DLLs is different. It does not have a class Object inherited from cwinapp. Therefore, you must set your own dllmain
Add the initialization code and end code for the function.
Compared with rule DLL:

1. It does not have an object derived from cwinapp;
2. It must have a dllmain function;
3. When dllmain calls the afxinitextensionmodule function, it must check the return value of this function. If 0 is returned, dllmmain also returns 0;
4. If you want to output a cruntimeclass object or resource, you must provide an initialization function to create a cdynlinklibrary object. In addition, it is necessary to output the initialization function;
5. the MFC application using extended dll must have a class derived from cwinapp, and the extended DLL initialization function is generally called in initinstance.

 

All functions output from the DLL should start with the following statement:
Afx_manage_state (afxgetstaticmodulestate ())
This statement is used to correctly switch the status of the MFC module.

When creating a DLL, VC ++ declares "_ cedcl" for the function, that is, if you do not make a special declaration when declaring your function, you
The created dll can only be called by C/C ++. If you want to call it in another development language (such as VB5.0), an error is reported even if the method is completely correct.

Ii. declaration types:

Iii. DLL files:
The modulo definition file (. Def) is composed of one or more modulo statements used to describe the DLL attributes.
Each. Def file must include a fixed Semantic Sentence in the lower module:
The first sentence must be a library sentence, indicating the name of the DLL.
The exports clause column lists the names of exported letters.
You can use the description statement to describe the DLL usage (this sentence is optional ).
";" For a row (optional)
Real-time file (. cpp file as an example)
In the. cpp file of the number of input table letters, the package contains the number of API letters and the number of export letters processed by the DLL entry points.

IV:
This article describes how to compile non-MFC DLLs: It is very convenient to use the VC wizard!
Statement:
Bool apientry dllmain (handle hmodule, DWORD ul_reason_for_call,

Lpvoid lpreserved)

{

Switch (ul_reason_for_call ){

Case dll_process_attach:

.......

Case dll_thread_attach:

.......

Case dll_thread_detach:

.......

Case dll_process_detach:

.......

}

Return true;

}
Each dll must have an entry point, just like an application written in C,
There must be a winmain function.
In this example, dllmain is a default entry function, and you do not need to write your own
And use the linker command line parameter toggle/entry declaration. Use this missing
The provincial entry function can correctly initialize the dynamic connection library when it is called. Of course, you
Do not enter the code that causes the system to crash during initialization.
In the parameter, hmoudle is a handle that points to itself when the dynamic library is called.
(In fact, it is a selector pointing to the _ dgroup segment)
Ul_reason_for_call indicates the reason why the dynamic library is called. When a process or thread
When loading or detaching a dynamic Connection Library, the operating system calls the entry function and describes the dynamic Connection Library.
The reason for the call. All its possible values are:
Dll_process_attach: The process is called.
Dll_thread_attach: The thread is called.
Dll_process_detach: the process is stopped.
Dll_thread_detach: The thread is stopped.
Lpreserved is a parameter reserved by the system.
The entry function has been written, and the rest is not difficult. You can add the file you want to enter
Functions, variables, C ++ classes, etc.

5. Compiling pure resource DLL

A pure resource DLL is a DLL that only contains resources, such as icons, bitmaps, strings, and sounds,
Video, dialog box, etc. Resource-only dll can save the size of executable files, and can be used by all
To improve the system performance. Compiling a pure resource DLL is much simpler than a common DLL,
First, create a Win32 DLL project, instead of an mfc dll, and then create a resource file *. RC, add
Add it to the resource DLL project. Then add an original file to initialize the DLL.
# Include <windows. h>
Extern "C"
Bool winapi dllmain (hinstance, DWORD dwreason, lpvoid)
{
Return 1;
}
This is the code required for pure resource DLL. Save this file as *. cpp. Compile the resource DLL.
Call the DLL shown in the application and use the loadlibrary function to load the resource DLL,
Use findresource and loadresource to load various resources, or use the following specific resource loading functions:

Formatmessage
Loadaccelerators
Loadbitmap
Loadcursor
Loadicon
Loadmenu
Loadstring
When the resource usage ends, your application must call the freelibrary function to release the resource.
The following describes how to call the compiled resource DLL.
First declare a DLL handle in the application, hinstance m_hlibrary; In the oncreate () function
Call loadlirbrary (), and call freelibrary () in ondestory (). Download a project file and take a look at everything.
Conventions:

Vi. Conventions: (this article is about ZZ rivershan ))

There are two types of conventions for the dynamic library output function: The call convention and the name modification convention.

1) Call Convention (calling convention): determines the order in which function parameters are transferred to and from the stack. The caller or the caller pushes the parameter to the stack, and the modifier conventions used by the compiler to recognize function names.

There are many function call conventions. Here is a simple introduction:

1. The _ stdcall call convention is equivalent to the Pascal call convention that is frequently used in 16-bit dynamic libraries. In 32-bit VC ++ 5.0, Pascal's call Convention is no longer supported (in fact, it has been defined as _ stdcall. In addition to _ Pascal, __fortran and _ syscall are not supported). Instead, they are replaced by the _ stdcall call convention. The two are essentially the same, that is, the function parameter is passed from right to left through the stack. The called function clears the memory stack of the transfer parameter before returning, but the difference is the function name modifier section (the modification section of the function name will be described in detail later ).

_ Stdcall is the default calling method of the PASCAL program. It is usually used in Win32 API. The function uses the stack pressure method from right to left and clears the stack when it exits. After compiling a function, VC adds an underline prefix to the function name, and adds "@" and the number of bytes of the parameter to the function name.

2. c call conventions (which are described by the _ cdecl keyword) are pushed to the stack in sequence from right to left. The caller pushes the parameters to the stack. The memory stack of the transfer parameter is maintained by the caller (because of this, the function that implements the variable parameter can only use this call Convention ). In addition, the function name modification conventions are also different.

_ Cdecl is the default call Method for C and C ++ programs. Every function that calls it contains the code to clear the stack. Therefore, the size of the executable file generated is larger than that of the call to the _ stdcall function. The function uses the stack pressure mode from right to left. After compiling a function, VC adds an underline prefix to the function name. Is the default MFC call convention.

3. The _ fastcall call convention is "person" as its name. Its main feature is fast because it transmits parameters through registers (in fact, it uses ECx and EDX to transmit the first two DWORD or smaller parameters, and the remaining parameters are still transmitted from the right to the left pressure stack, the called function clears the memory stack of the transfer parameter before returning). In terms of the function name modification conventions, it is different from the previous two.

_ Fastcall functions use registers to pass parameters. After compiling a function, VC adds the "@" prefix to the function name, and adds "@" and the number of parameters after the function name.

4. thiscall is only applied to "C ++" member functions. This pointer is stored in the Cx register and the parameter is pressed from right to left. Thiscall is not a keyword and cannot be specified by programmers.

5. Naked call uses 1-4 call timing. If necessary, the compiler will generate code to save the ESI, EDI, EBX, and EBP registers when entering the function, when you exit the function, the code is generated to restore the content of these registers. Naked call does not generate such code. The naked call is not a type modifier, so it must be used together with _ declspec.

The keywords _ stdcall, _ cdecl, and _ fastcall can be directly added before the function to be output, or in the setting environment... select/C ++/code generation. When the keywords added before the output function are different from those selected in the compiling environment, the keywords directly added before the output function are valid. Their corresponding command line parameters are/GZ,/GD, And/GR. The default status is/GD, Which is _ cdecl.

To fully imitate Pascal's call convention, you must first use the _ stdcall call Convention. As for the function name Modification Convention, you can use other methods to imitate it. Another thing worth mentioning is winapi macro, windows. h supports this macro. It can translate the function into an appropriate call convention. In Win32, it is defined as _ stdcall. You can use the winapi macro to create your own APIs.

2) Name modification conventions

1. decoration name)

The "C" or "C ++" functions are identified by modifier internally (Compilation and link. Modifier is a string generated by the compiler when compiling a function definition or prototype. In some cases, modifying the name of a function is necessary, for example, specifying the output "C ++" overload function, constructor, and destructor in the module definition file, for example, call the "C" or "C ++" function in the assembly code.

Modifier names are jointly determined by function names, class names, call conventions, return types, parameters, and so on.

2. The name Modification Convention varies with the call convention and the compilation type (C or C ++. The function name modification conventions vary with the compilation type and call conventions.

Rules for modifying function names during a and c Compilation:

The _ stdcall call Convention adds an underline prefix before the output function name, followed by the "@" symbol and the number of bytes of the parameter. The format is _ functionname @ number.

The _ cdecl call Convention only adds an underline prefix before the output function name in the format of _ functionname.

_ Fastcall: add the "@" symbol before the output function name, followed by the "@" symbol and the number of bytes of the parameter. The format is @ functionname @ number.

They do not change the case sensitivity of the output function name. This is different from Pascal's call conventions. Pascal's output function names are not modified and all are capitalized.

B. Conventions for function name modification during C ++ Compilation:

_ Stdcall call conventions:
1. Take "?" Start of the function name, followed by the function name;
2. The parameter table starts with "@ YG" after the function name, followed by the parameter table;
3. The parameter table is represented in code:
X -- void,
D -- char,
E -- unsigned char,
F -- short,
H -- int,
I -- unsigned int,
J -- long,
K -- unsigned long,
M -- float,
N -- double,
_ N -- bool,
....
Pa -- indicates the pointer. The code behind the pointer indicates the pointer type. If a pointer of the same type appears consecutively, it is replaced by "0". A "0" indicates a repetition;
4. the first item of the parameter table is the type of the return value of the function, followed by the Data Type of the parameter. the pointer ID is prior to the Data Type indicated by the parameter;
5. mark the end of the entire name with "@ Z" after the parameter table. If this function has no parameter, it ends with "Z.

The format is "? Functionname @ YG ***** @ Z "or"? Functionname @ YG * xz ", for example
Int test1 (char * var1, unsigned long) ----- "? Test1 @ yghpadk @ Z"
Void Test2 () ----- "? Test2 @ ygxxz"

_ Cdecl:
The rules are the same as the _ stdcall call Convention above, except that the start mark of the parameter table is changed from "@ YG" to "@ ya ".

_ Fastcall:
The rules are the same as the _ stdcall call Convention above, but the start mark of the parameter table is changed from "@ YG" to "@ Yi ".

The "_ cedcl" Declaration for the function can only be called by C/C ++.

Extern "C" {void _ declspec (dllexport) _ cdecl test (INT var );}
The output function is named test.
 
MFC provides some macros for this purpose.

Afx_class_import :__ declspec (dllexport)
 
Afx_api_import :__ declspec (dllexport)
 
Afx_data_import :__ declspec (dllexport)
 
Afx_class_export :__ declspec (dllexport)
 
Afx_api_export :__ declspec (dllexport)
 
Afx_data_export :__ declspec (dllexport)
 
Afx_ext_class: # ifdef _ afxext
Afx_class_export
# Else
Afx_class_import
 
Afx_ext_api: # ifdef _ afxext
Afx_api_export
# Else
Afx_api_import
 
Afx_ext_data: # ifdef _ afxext
Afx_data_export
# Else
Afx_data_import

Macros such as afx_ext_class, if used in the implementation of DLL applications, it indicates the output (because _ afx_ext is defined, it is usually specified in the identifier parameter of the compiler/d_afx_ext ); if it is used in an application that uses DLL, it indicates the input (_ afx_ext is not defined ).

To output the entire class, use _ declspec (_ dllexpot) for the class. to output the member function of the class, use _ declspec (_ dllexport) for the function ). For example:

Class afx_ext_class ctextdoc: Public cdocument
{
...
}

Extern "C" afx_ext_api void winapi initmydll ();

Among these methods, the third method is recommended for ease of use. The second method is the first method. If output by sequence number, the call efficiency is higher. The second method is the second method.

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.