Learn DLL (2) ------ Win32 Snap Dynamic Link Library (DLL) Program Principle

xiaoxiao2021-03-06  20

Deep Detecting the principle of Win32 Switch Link Library (DLL) Programming Program

Topic: DLL is the most important component of Windows, many new features in Windows, new features are implemented by DLL, so master it, it is very important. Dynamic Link Library can not only be used as a run module, including function code, but also any data or resource (bitmap, icon, etc.) other than the program. The dynamic link library is to provide functions or resources to the application. The DLL is a disk file (usually with a DLL extension), which consists of global data, service functions, and resources, which are part of the calling process in the virtual space that is loaded into the process at runtime. At runtime, the system is loaded into memory space only when the exe program does call these DLL modules. Each process copies its own read / write global variable. If you want to share memory with other processes, you must use a memory map file or declare a shared data segment. The stack memory required by the DLL module is allocated from the stack of the runtime process. A DLL file contains an export function table. These export functions are linked by their symbolic names and integers called identification number.

Import Export Functions: In the DLL code, you must explicitly declare the export function as described below: __DECLSPEC (DLLEXPORT) INT MyFunction (INT N); but can also list the export function in the module definition (DEF) file, but this is often caused More trouble. In terms of application, the requirements are required to clearly state the corresponding input function: __DECLSPEC (DLLIMPORT) INT MyFunCITION (INT N); (this is implicit link DLL) only import and export declarations do not make the internal function call inside the application Link to the corresponding DLL file. The application's project must specify the desired input library (lib file) for the linker. Moreover, the application must instance must include at least one call to the DLL function. Implicit link and explicit link DLL

Explicit: Typedef Double (SQRTPROC) (Double);

Hinstance hinstance; // Set global variables for storing DLL handles SQRTPROC * PFUNCTION; second variable showme is a pointer Verify (hinstance = :: loadLibrary "in the library," c: // WinNT // system32 // MYDLL.DLL "); verify (pfunction = (sqrtproc *) :: getProcadDress (Hinstance," Squareroot "); double d = (* pfunction) (81.0); // call the DLL function implicit: programmer Static link mode When generating an application, the call function in the application matches the export symbol in the lib file, these symbols or identification numbers enter the generated EXE file. Implicit links and explicit link DLL distinction: In hidden In the way, all DLL files called by the application are loaded in the memory when the application exec is loaded; but if the explicit link mode is used, the programmer can determine when the DLL file is loaded or not loaded.

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 into the process, but also when the DLL module is separated from the process (and other time) is also called. Each DLL module in the process is identified by the globally unique 32-byte Hinstance handle. The process yourself have a Hinstance handle. All of these module handles are only valid within a particular process, which represents the starting address of the DLL or EXE module in the process virtual space. Looking for the path to the DLL: Windows will follow the search order below to locate the DLL: 1. Contains the directory of the EXE file, 2. The current working directory of the process, 3. Windows system catalog, 4. Windows catalog, 5. A series of directories listed in the PATH environment variable. Important:

I: The provincial missword of the DLL file is consistent with the engine name (also the name after library in the .def file), do not try to change it by simply modify the file name of the.dll file after the production is completed, which will cause Use this DLL application error.

Two functions are defined in the DLL: ExportFunction: You can call internal functions (INTERNALFUNCTION) by other modules: can only be used inside the DLL

The MFC-based DLL does not apply to the DLL that reads binary files (not easy to transplant, the binary file shared with DOS applications) The API-based DLL can correctly read the binary created in the DOS environment. Pure standard Function DLL can be used in many platforms! (The strongest transplantability) In order for other languages: Unless you absolutely need C encoding, I still recommend C to write DLL. DLL Type under the VC: Non-MFC DLL: Refers to the class library structure that does not need to be MFC, directly written by the C language, the function of its output is generally standard C interface, and can be written by non-MFC or MFC The application is called. LL,

Regular DLL: Like the Extension DLLs described below, it is written in the MFC class library. Obviously, there is a class inherited CWINAPP in the source file. It can also be subsequently connected to the MFC and dynamically connected to the MFC. But static connection to MFC dynamic connection libraries are only supported by VC's professional and enterprise version.

Extension DLL: Used to achieve the reuse of classes inherited from the MFC, that is, with this type of dynamic connection library, can be used to output a class inherited from the MFC. The Extension DLL is created using the MFC's dynamic connection versions, and it is only called by the application written by the MFC class library. The reuse of the class that is inherited from the MFC, that is, with this type of dynamic connection library, can be used to output a class that is inherited from the MFC. Its output function can only be used with MFC and dynamically link to the MFC application. You can inherit your you want from the MFC, more suitable for your own class, and provide it to your app. You can also provide you with an object pointer for MFC or MFC inherited class. The Extension DLL is created using the MFC's dynamic connection versions, and it is only called by the application written by the MFC class library. Extension DLLS and Regular DLLS are different, it does not have an object that is inherited from cwinapp, so you have to add initialization code and end code for your own DLLMAIN function. Compared with the rule DLL, there is a difference:

1, there is no object derived from cwinapp; 2, it must have a DLLMAIN function; The CRUntimeClass type object or resource (Resources), you need to provide an initialization function to create a cdynlinklibrary object. Also, it is necessary to output the initialization function; 5, the MFC application using the extended DLL must have a class derived from the CWINAPP, and generally call the extension DLL initialization function in InitInstance. All functions output from the DLL should start with the following statement: AFX_Manage_State (AFXGETSTACModuleState ()) This statement is used to switch the MFC module status correctly.

When making a DLL, the provincial deficiency of VC is "__CEDCL", that is, if you don't make a special statement when you declare your function, the DLL you make can only be called by C / C , if you want To call it with another development language (such as VB5.0), it will report an error, even if the call method is completely correct.

Second: Declaration Type Detailed:

Three: DLL to be filed: Module definition file (.def) is a text file consisting of one or more module statements for describing DLL properties, each .def file must contain at least the following module definition statement: first The statement must be a library statement, pointing out the name of the DLL. The exports statement lists the names of the exported function. The use of the DLL can be described using the Description statement (this sentence is optional). ";" For a line of incoming annotations (optional) real file (.CPP documents as an example) real entry table function. In-cPP file, package the API function and the code that exports the function of the DLL entry point.

4: Introducing the Writing method of Non-MFC DLLS: If you use VC's wizard, it is very convenient! Writing: 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 the application we write with C, there must be a Winmain function. In this example, DllMain is a default entry function, you don't need to write your own DLL entry function, and declare the parameter switch / entry declared with the command line of Linker. With this default entry function, you can get the correct initialization when the dynamic connection library is called. Of course, you don't fill in the code that crashes the system when you initialize. In the parameter, hmoudle is a handle that is passed when the dynamic library is called (actually, it is a selector pointing to the _dgroup segment) ul_reason_for_call is a sign of the cause of the dynamic library. When a process or thread is loaded or unloaded, the operating system calls the entry function and describes the reason why the dynamic connection library is called. All possible values: 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 entrance function has been written, the rest is not difficult, you can join the functions or variables you want to output or the C class, etc. you want to output, and write a copy of the DLL

Pure resource DLL is a DLL containing only resources, such as icons, bitmaps, strings, sounds, videos, dialogs, etc. Using a pure resource DLL can save the size of the executable file, which can be shared by all applications, thereby improving system performance. Pure resource DLL writing is more simple than ordinary DLLs, first create a Win32 DLL project, not the MFC DLL, then create a resource file * .rc, add to the resource DLL project. Then add an original file that initializes the DLL. #include Extern "C" Bool WinApi DLLMain (Hinstance Hinstance, DWORD DWREASON, LPVOID) {Return 1;} This is the code that must be required by the pure resource DLL, saving this file to * .cpp. Compile this resource DLL. Calling this DLL in the application, using the LoadLibrary function to load resource DLL, FindResource, and LoadResource to load a variety of resources, or use the following specific resource load functions:

FormatMAGELERATORS LOADBITMAP LOADCURSORS LOADICON LOADMENU LOADSTRING When the resource is used, your application must call the FreeELibrary function to release the resource. Let's talk about how to call the written resource DLL first declare a DLL handle in the application, hinstance m_hlibrary; call loadLirbrary () in the onCreate () function, call FreeELibrary () in OnDestory (). Download a project file to see, let's get it. About the agreement:

Sixth, on the agreement: (this point is six zz rivershan (original))

There are two conventions for dynamic library output functions: call conventions and name modifications.

1) Calling Convention: Decide the order of the stack and out of the stack when the function parameter is transmitted, and the argument is bounced by the caller or the caller, and the compiler is used to identify the modification of the function name.

The function call is agreed to have a variety, here is simple to say:

1. __ stdcall calls agreement equivalent to the PASCAL call convention used in the 16-bit dynamic library. In the 32-bit VC 5.0, the PASCAL call convention is no longer supported (in fact it has been defined as __stdcall. In addition to __pascal, __ fortran and __syscall are not supported), replaced by __stdcall call agreement. The two are substantially consistent, that is, the function's parameters pass the right left through the stack through the stack, the called function is returned to the memory stack of the transfer parameters, but the different part of the function name (about the modified part of the function name) The detailed description will be described later. _stdcall is the default call mode of the Pascal program. It is usually used in the Win32 API. The function uses the stack of right to left, and the stack is cleared when you exit. The VC compiles the function before adding a downline prefix in front of the function name, plus the number of bytes of "@" and parameters after the function name.

2, c call convention (ie, using __cdecl keyword description) Press the parameter from right to left, and populates the argument by the caller. For the memory stack of the transfer parameters, it is maintained by the caller (for this, the function that implements variable parameters can only use the call convention). In addition, there is also different in terms of function name modification.

_CDECL is the default call mode of the C and C programs. Each function that calls it contains the code that clears the stack, so the resulting executable size is larger than the call _stdcall function. The function uses the stack of right to left. VC compiles the function and adds a downline prefix in front of the function name. It is an MFC default call convention.

3, __ fastCall call agreement is "person", such as its name, its main feature is fast, because it passes the parameter through the register (actually, it uses ECX and EDX to transfer the first two double words (DWORD) or smaller The parameters, the remaining parameters are still transmitted to the left stack, the called function is returned to the internal memory stack of the transfer parameters before returning), and in terms of the function name modification, it is different from the top.

_fastCall mode functions use register pass parameters, and VC compiles the function after the "@" prefix in front of the function name, add the number of bytes of "@" and parameters after the function name.

4. ThisCall is only applied to the "C " member function. The THIS pointer is stored in the CX register, the parameter is left from right to left. Thiscall is not a keyword, so it cannot be designated by the programmer.

5, Naked Call When using 1-4 call conventions, if necessary, the compiler generates code to save the ESI, EDI, EBX, EBP registers, generate code recovery of these registers when entering the function. Naked Call does not produce such a code. Naked Call is not a type modifier, so you must use the _declspec.

Keywords __stdcall, __ cdecl, and __fastcall can be selected before the functionality of the function you want to output, or you can choose the SETTING ... / C / C / Code Generation item of the compilation environment. When the keyword before the output function is not in the compilation environment, the keyword before the output function is added directly before the output function is valid. The corresponding command line parameters are / Gz, / GD, and / GR, respectively. The default state is / gd, ie __cdecl.

To fully imitate the Pascal call, you must first use the __stdcall call convention, as for the function name modification, can be imitated by other methods. There is also a WINAPI macro, Windows.h supports this macro, which can translate the function into an appropriate call agreement, in Win32, it is defined as __stdcall. Use WinAPI macros to create your own APIS. 2) Name modification agreement

1, Decoration Name

"C" or "C " function is identified by a modified name inside (compiled and link). The modisle name is a string generated when the compiler is generated when the compile function is defined or the prototype. Some cases are necessary to use the modifier of the function, such as the output "C " overload function, constructor, the structure, the destructor, and call "C" or "C " function in the assembly code. Wait.

The modified name, class name, call agreement, return type, parameter, etc.

2, the name modification will change with the adjustment agreement and the compilation species (C or C ). The function name modification is different from the compilation species and the call agreement, and below will be explained.

A, C compile time function name modification agreement rules:

__stdcall call agreed to add a downline prefix before the output function name, and then a "@" symbol and its parameters of the number of bytes, the format is _functionName @ number.

__cdecl call conventions only add a downline prefix before the output function name, format is _functionName. __Fastcall call agreed to add a "@" symbol before the output function name, the later is also a "@" symbol and its parameters, the format is @ functionName @ number.

They do not change the case sensitive in the output function name, which is different from the PASCAL call, and the function name of the Pascal agreed output without any modification and all uppercase.

B, C compile function name modification agreement rules:

__stdcall call convention: 1, with "?" identification function name, then follow the function name; 2. After the function name is labeled with the "@@ YG" identifier, the parameter table; --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 - represents a pointer, the subsequent code indicates the pointer type, if the same type of pointer continuously appears, instead of "0", a "0" represents a repetition; 4, parameter table The first item is the return value type of the function, thereafter, the data type of the parameter, the pointer identifies the end of its index; 5, after the parameter table identifies the end of the entire name, if the function No parameters, the end is ended in the "Z" identity.

The format is "? Functionname @@ yg ***** @ z" or "functionname @@ yg * xz", such as int test1 (char * var1, unsigned long) ----- "Test1 @@ yghpadk @Z "Void Test2 () -----"? Test2 @@ ygxxz "__ cdecl call agreement: Rule the above _stdcall call convention, just the start identification of the parameter table is changed from the above" @@ yg "@@ @@ YG" @YA.

__fastcall call convention: Rule the above _stdcall call convention, just the start identification of the parameter table changes from the "@@ yg" above "@@ yi".

The province of VC to function is "__CEDCL", which will only be called by C / C . EXTERN "C" {void __declspec (dllexport) __cdecl test (int var);} The output function name is: Test MFC provides some Macro, there is such a role.

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

Macro like AFX_EXT_CLASS, if used in the implementation of the DLL application, indicates the output (because _afx_ext is defined, it is usually specified in the identity parameter of the compiler to specify this option / D_AFX_ext); if used to use the DLL application In, the input is indicated (_AFX_ext is not defined).

To output the entire class, use _DECLSPEC (_dllexpot) to class; use the member function to output the class, using _declspec (_dllexport). Such as:

Class AFX_EXT_CLASS CTEXTDOC: PUBLIC CDocument {...}

EXTERN "C" AFX_EXT_API VOID WINAPI INITMYDLL ();

In these methods, it is best to use the third, convenient to use; second is the first, if the sequence number is output, the call efficiency will be higher; the most second.

转载请注明原文地址:https://www.9cbs.com/read-40930.html

New Post(0)