Tuesday, January 11, 2011

VC + + dynamic link library foundation of programming concepts generous

 VC + + dynamic link library foundation of programming concepts
2005-10 of generous: Song Baohua Source: NEW YORK

1. Introduction to elaborate on the first DLL (Dynamic Linkable Library) concept, you can simply put DLL as a warehouse, it offers you some can be directly used with the variable, function or class. in the history of the warehouse has experienced dynamic link library is shared code in a way, if you use a static link library, whether you are willing, lib of the instructions have been directly included in the resulting EXE file the. but if the use of DLL, the DLL do not have to be included in the final EXE file, EXE file can perform link library or static library, and in the dynamic link library can be included in the other dynamic or static link library.
the dynamic link library, we need to establish the following concepts: (1) DLL for preparation and specific programming language and compiler independent as long as the interface to follow the agreed specifications and calling DLL method DLL written in various languages can call each other. For example, Windows provides a system DLL (which includes the Windows-API), in any development environment can be call, do not care about it is the Visual Basic, Visual C + + or Delphi. (2) dynamic link library can be seen everywhere we system32 in the Windows directory folder to see kernel32.dll, user32.dll and gdi32.dll, windows most of the API are included in the DLL,. kernel32.dll function in the main processing memory management and process scheduling; user32.dll main control functions in the user interface; gdi32.dll in terms of function is responsible for graphics operation. the average programmer have used a function similar to MessageBox, in fact, it is included in the dynamic link library user32.dll. This shows that DLL is not unfamiliar to us. (3) VC classification of the dynamic link library supports three Visual C + + DLL They are Non-MFC DLL (dynamic libraries of non-MFC), MFC Regular DLL (MFC rules DLL), MFC Extension DLL (MFC extension DLL). Non-MFC dynamic libraries do not use MFC class library structure, the export function as a standard C interface, can be written in non-MFC or MFC application calls; MFC rules DLL contains a class that inherits from CWinApp, but no message loop; MFC MFC extension DLL The dynamic link version used to create, it can only be used MFC libraries are invoked by applications written in. Since this length is longer, more content, is bound to need to read the article on the description of the relevant matters, the following questions and answers given in the form. Q: What are the contents of this paper to explain? A: This DLL described in detail all aspects of programming, to end of this article can be a more comprehensive grasp of DLL, and can write most of the DLL program. Q: how to read this article? A: This article explains each topic with the source code for all cases process, with the text can be downloaded (each project by WINRAR compressed). All of these routines written by the author and debug in VC + +6.0 to. of course, not the reader understand the ultimate goal of this article, readers should be hands-on practice truly grasp the DLL's secret. Q: Learning this and what kind of basic knowledge? A: If you have mastered C, and generally master the C + +, to understand a bit MFC knowledge, you can easily read this article. 2. Static Link Library to explain the static link library is not the focus of this article, but before the specific DLL to explain, through the example of a static link library to help us quickly establish a br> as shown in Figure 1, in a VC + +6.0 in the new name for libTest the static library project (click here to download the project), and New lib.h and lib.cpp two files, lib.h and lib. cpp source code is as follows:
/ / File: lib.h # ifndef LIB_H # define LIB_Hextern / / File: lib.cpp # include library, which provides add functionality. the header files and. lib file to the user, the user can add them directly using the function. standard Turbo C2.0 of the C library functions (we use the scanf, printf , memcpy, strcpy, etc.) to come from this static library. Let's look at how to use the library, where construction work in the area libTest a libCall new project. libCall project contains only one main.cpp file, which shows the static link library called method, and its source code is as follows:
# include # include lib library call is as simple as perhaps we are using every day, but we do not understand this concept. code # pragma comment (lib, generated. obj file should be connected together with the libTest.lib. If you do not specify # pragma comment, you can directly set in the VC + +, as shown in Figure 2, select tools, options, directories, library files menu or option, fill in the library file path. red circle in Figure 2, plus some added libTest.lib our path to the file.
Figure 2 in the VC set the library path
example of the static link library at least let us know the library functions how the matter, they come from. We now have a vague understanding of the following: (1) library is not a monster, the preparation of the library program and the preparation of the general procedures are not very different, but libraries can not be separately; (2) library available to other programs that can call the East, another program to call it must be specified in some way it wants to call it. more analysis from a static link library and get the silly notion of the library can be directly extended to the dynamic link library , the dynamic link library and static link library and call in the preparation of the different reflected in the library on the external interface of a slightly different definition and call the method.
3. the library into the debugger and see all kinds of DLL's in specific detail before it is necessary to debug library and view what the method described as beginning from the next section, we will face a lot of examples of projects. Because the libraries alone can not perform, so press the F5 (start debug mode execution) or CTRL + F5 (run) is executed, it pops up the dialog box shown in Figure 3, requires the user to enter the path to the executable file to start the implementation of library functions. This time we enter the call the library path to EXE file can be debug library, and its application engineering and general debugging techniques to debug the same.
Figure 3 library commissioning and Application Engineering (call the library project) placed in the same VC workspace, application engineering for debugging only, call the library at the application engineering function to set a breakpoint at the statement, the Executive and then press F11, so step into the library function. The first two projects in the libTest and libCall placed into the same work area, the project structure shown in Figure 4.
Figure 4 library project and call the library project into the same workspace to debug < br> The debugging method and the static link library dynamic link library in terms of the same. Therefore, this article provides all the source code download contains a library project and call the library project, which both are included in a work area This is the author's intention to provide this package to download is located. dynamic link library can be used in the export interface of Visual C + + Depends tool to view, let us turn on the system directory Depends user32.dll, see? red circle Several versions of the MessageBox is it! had it really here, ah, ah here it is the original!
Figure 5 View DLL
course with Depends Depends tool can also display the hierarchy of DLL, if the use it Open an executable file, you can see what the executable file called a DLL. well, let's formal entry into the dynamic link library of the world, first to look at the most common DLL, that is non-MFC DLL.VC + + Dynamic Link Library Programming non-MFC DLL
4.1 with a simple DLL Section 2 gives way to static link library function interface provides the methods add, and then we look at how to implement a dynamic link library with the same functions add function.
document.write (), because with the MFC AppWizard (dll) will be established to be described in Section 5,6 MFC dynamic link library.
Figure 6, a non-MFC DLL
in the establishment of the project and add lib.h lib . cpp files, source code is as follows:
/ * File Name: lib.h * / # ifndef LIB_H # define LIB_Hextern Name: lib.cpp * / # include work with the DLL project in the same area of the application engineering dllCall, it calls the DLL functions in the add, its source code is as follows:
# include # include typedef int (* lpAddFun) (int, int); / / macro defined function pointer type int main (int argc, char * argv []) {HINSTANCE hDll; / / DLL handle lpAddFun addFun; / / function pointer hDll = LoadLibrary ( Debug   dllTest.dll ; printf (is lib.h before the declaration of the function add to add the __declspec (dllexport) statement. This is the meaning of a statement function statement, add the DLL's exported functions. DLL functions within the two types: (1) DLL exported functions can be program calls for the supply; (2) DLL internal functions, procedures can only be used in the DLL, the application can not call them. and the application calls the DLL and static link library section 2, there are large differences in the call, let to each analysis. First of all, the statement typedef int (* lpAddFun) (int, int) and add the definition of a function accepts parameters and return values are the same type of function pointer type. Then, in the main function of the instance defined lpAddFun addFun; Second, the main function defined in a DLL HINSTANCE handle instances hDll, through the LoadLibrary Win32 Api function dynamically loads the DLL module and DLL module handle assigned to the hDll; again, in the function main, obtained by GetProcAddress Win32 Api function a function of the loaded DLL module and add the address assigned to the addFun. addFun conducted by the function pointer in the add function on the DLL calls; Finally, after the project finished using DLL, in the main function through the release of Win32 Api function FreeLibrary the already loaded DLL module. Through this simple example, we learn the definition and DLL calls the general concept: (1) DLL in a particular way to be declared to the exported functions (or variable, class); (2) applications project to be called in a particular way of DLL export functions (or variable, class). Now we come to the species are given in Section 4.1 examples with the statement in the function __declspec (dllexport), this is no longer an example; Another way is to use module definition (. def) file a statement,. def files provided for the linker For the program to be linked to export, property and other information. The following code shows how the same. def files will be exported DLL function declare function add (to be added to the project in dllTest lib.def file):
; lib . def: Export DLL functions LIBRARY dllTestEXPORTSadd @ 1
. def files of the rules: (1) LIBRARY statement instructions. def file corresponding DLL; (2) EXPORTS statement lists after the name of the function you want to export. can. def file export function name followed by @ n, said the serial number you want to export the function, n (during the function call, this number will play its role); (3). def file comments by each comment beginning of the line of the semicolon (;) designation, and the comments can not share the line with the statement. It can be seen, the meaning of the example to generate lib.def file named function, and specify the function of the number add to 1. 4.3 DLL call form the example in section 4.1, we see from the -DLL Release contained, explicit link which loaded at runtime DLL files the decision. and dynamic calling of static methods that call the corresponding methods, Jing and go to the DLL inside the call is divided into static and dynamic ways. said: Application of the DLL loading and unloading DLL end of the process. When the application calls the end of a DLL, if the system there are other programs to use the DLL, the Windows application log on the DLL minus 1, until all the use of the DLL The programs are free until the end of it. static call is simple and practical, but not as dynamic invocation flexible. Let us look at an example of static call (click here to download the project) will be generated by the compiler dllTest works. lib and. dll files copyed dllCall project the path of the, dllCall the following code:
# pragma comment (lib, location information extern , result); return 0;}
can be seen from the above code, the static call to smooth the way to complete two actions: (1) tell the compiler and the corresponding DLL. lib file path and file name where the , # pragma comment (lib, symbolic name and serial number (does not contain the actual code). in the application,. lib file will be compiled DLL in an alternative file. (2) a statement to import function, extern x, int y) statement __declspec (dllimport) to play this role. Static method no longer need to use the system call API to load, unload DLL and access to exported DLL function address. This is because, when the programmer through the static way links compiled application, the application and call. lib file export symbols will match the function symbols into the generated EXE files,. lib file contained in the corresponding DLL file name The compiler is also stored in the EXE file inside. When the application is running when you need to load the DLL file, Windows will find the information and load DLL, and then through the symbolic name of the DLL functions to achieve dynamic linking. so, EXE will directly by the output of the function name calling DLL functions, like call other functions within the same program.
4.4 DllMain function of Windows, when loading the DLL, you need an entry function, just like the main console or DOS program needs to function , WIN32 application needs WinMain function is the same. In the previous example, DLL does not provide DllMain function, application engineering can successfully invoke DLL, this is because Windows can not find the DllMain, the system will be introduced from other in a runtime no action version of the default DllMain function, does not mean you can abandon DLL DllMain function. According to the preparation of specifications, Windows should find and execute the DLL's DllMain function in the DLL as a basis for loading, it makes the DLL to be retained in memory . This function does not belong to export functions, but the DLL's internal functions. This means that the project can not be directly referenced in the application DllMain function, DllMain is called automatically. We look at a DllMain function example (click here to download this project).
BOOL APIENTRY DllMain (HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {switch (ul_reason_for_call) {case DLL_PROCESS_ATTACH: printf ( nthread attach of dll br> DllMain function in the DLL is loaded and unloaded is called, in a single thread startup and termination, DLLMain functions have been called, ul_reason_for_call indicates the reason is called. The reason there are four kinds, namely PROCESS_ATTACH, PROCESS_DETACH, THREAD_ATTACH and THREAD_DETACH to switch statement listed. DllMain a closer look at the function s head BOOL APIENTRY DllMain (HANDLE hModule, WORD ul_reason_for_call, LPVOID lpReserved). APIENTRY is defined as __stdcall, which means that the function to be called the standard way of Pascal, but also is WINAPI way; process for each DLL module is a 32-byte globally unique ID HINSTANCE handle, only valid within a particular process, handle the process on behalf of the DLL module starting address of the virtual space. In Win32,, HINSTANCE HMODULE values and the same, these two types can replace the use of, this is the origin of function parameters hModule. execute the following code:
hDll = LoadLibrary (dll (2, 3); printf (: 5process detach of dll
verify the output of the order of the time DllMain is called. code GetProcAddress (hDll, MAKEINTRESOURCE (1)) It should be noted that it directly. def file for the add function to access the specified sequence number add function, embodied in the MAKEINTRESOURCE (1), MAKEINTRESOURCE is a serial number to get through the macro function name, defined as (taken from winuser.h):
# define MAKEINTRESOURCEA (i) (LPSTR) ((DWORD) ( (WORD) (i))) # define MAKEINTRESOURCEW (i) (LPWSTR) ((DWORD) ((WORD) (i))) # ifdef UNICODE # define MAKEINTRESOURCE MAKEINTRESOURCEW # else # define MAKEINTRESOURCE MAKEINTRESOURCEA
4.5 __stdcall convention if written by VC + + DLL For programs written in other languages it is called, should call the function declared as __stdcall way way, WINAPI have adopted this approach, the C / C + + method is called the default mode for the __cdecl.__stdcall __cdecl function name with the end of the symbol generated in different ways. the use of a C compilation mode (in C + +, need to declare the function as extern ; @ __cdecl and __stdcall and macro are relevant (Adapted from windef.h):
# define CALLBACK __stdcall / / This is the legend of the callback function # define WINAPI __stdcall / / This is the legendary WINAPI # define WINAPIV __cdecl # define APIENTRY WINAPI / / DllMain entry here # define APIPRIVATE __stdcall # define PASCAL __stdcall
in lib.h, we should add this function declaration:
int __stdcall add (int x, int y) ;
function pointer in the application of project types should be defined as:
typedef int (__stdcall * lpAddFun) (int, int);
if the function is declared as __stdcall lib.h will call, and the application projects still use typedef int (* lpAddFun) (int, int), run-time error will occur (because the type does not match the project is still in the application of the default __cdecl calling), pop-up dialog box shown in Figure 7 .
Figure 7 does not match the calling convention to run when the error
Figure 8 that those remarks have actually given the wrong reason, that download the example project source code __stdcall calling.
4.6 DLL DLL export variables defined global variable can be called the process of access; DLL calling process can access the global data, we take a look at the project referenced DLL in the application of variable Examples (Click here to download the project). 

No comments:

Post a Comment