DLL foundation

xiaoxiao2021-03-05  53

This article is written in the case of checking the information. There is also a good summary of yourself in DLL. Some non-useless nonsense written in front, since Microsoft launched the first version of the Windows operating system, Link Library (DLL) has always been the foundation of the Windows operating system. Dynamic link libraries usually cannot run directly, or messages cannot be received. They are some independent files that contain functions that can be executable or other DLL calls to complete a work. It works only when other modules call functions in the dynamic link library. All functions in the Windows API are included in the DLL. There are 3 most important DLLs, kernel32.dll, which contain individual functions for managing memory, process, and threads; user32.dll, which contains user interface tasks (such as creation and messages of windows) Each function; GDI32.DLL, which contains each function for drawing and displaying text. Static library and dynamic library static library: Functions and data are compiled into a binary (usually extension .lib). In the case of using a static library, when compiling the link executable file, the linker copies these functions and data from the library and combines them with other modules of the application to create the final executable (.exe file). When using dynamic libraries, two files are often provided: an introduction library and a DLL. The introduction library contains the symbolic names of the functions and variables exported by the DLL, and the DLL contains the actual functions and data. When compiling the link executable, only the link introduction library, the function code and data in the DLL are not copied to the executable, when running, then load the DLL, access the functions exported in the DLL. The benefits of using dynamic link libraries can be written in a variety of programming languages. Enhance the function of the product. Provide a secondary development platform. Simplify project management. Can save disk space and memory. Helps resource sharing. It helps to realize the localization of the application. Dynamic link library is accessed by multiple processes

Dynamic link library loaded two ways

Preparatory knowledge

::::: :::::::::::::::::::::: ::::::::::::::

Process virtual address space:

In 32 is system, the system is allocated to allocate 2 ^ 32 address space.

Specifically, see "Windows Core Programming"

Preprocessing command:

Nothing can be said

Take a look at the code! !

Environment variable: (The concept of environment variables I will not introduce, specific to the Windows core programming, there is a very detailed description) to put the DLL to the currently any environment variable can load the defined function pointer.

Format: typedef int (* proc) (Int A, INT B);

Note: PROC is a function pointer type instead of a variable

Then we can define variables with this pointer type.

Proc myProc; here myProc is a pointer variable

If it is really boring, you can go to this website to see the function of the function http://ufo.tyedu.com/study/programmer/language_c/200412/1472.html

The call settling of functions (you can not know, but you can understand the DLL's call after understanding)

Calling convention for functions: Function call conviction is a convention for the function calorie and the modified function bodies regarding parameter delivery, return value delivery, stack clearance, register use; it is a powerful, function call, function call, function call If you use different call agreements, you will be able to perform errors, you must see it as part of a function declaration;

Common function call conventions:

Function call conventions in VC6:

Call the agreed stack clearance parameter transfer __cdecl caller from right to left, pass the __stdcall function body from right to left, by stack pass __fastcall function body from right to left, prioritize the register (ECX, EDX), then use the stack THISCALL function Body THIS pointer default via ECX, other parameters from right to left in the stack

__cdecl is the default call agreement of C / C ; there is no THISCALL in the invocation convention, which is the default call agreement of the class member function; the call agreement of the main (or wmain) function in C / C must be __cdecl, Do not allow changes; the default call agreement can generally be changed through the compiler settings. If your code rely on the call agreement, please clearly indicate the invocation agreement required to use;

In the common function call convention, only CDECL agrees require caller to clear the stack; the function in C / C supports the number of parameters of parameters, such as the Printf function; because the function is not known to press the caller in the stack, how many parameters Therefore, the function should not be convenient to know how to clear the stack, then the best way is to give the clearance stack to the caller; this should be the reason for the CDECL call convention;

VB generally uses STDCALL call conventions; (PS: Is there a stronger guarantee) Windows API, generally uses STDCALL conventions; (PS: Is there a stronger guarantee) suggest in call between different languages ​​( For example, DLL is best adopted by STDCALL calls because it supports the best language compatibility;

Three: Function Return Value Transfer Method In fact, the return value will also imagine an OUT-shaped parameter for function calls; function return value transmission mode is also part of the function call; if there is a function of return value, time INT 32bit data values ​​such as pointers (including 32bit structure) pass through EAX, (Bool, Char passed through Al, Short passed through AX delivery), special __int64, etc. 64bit structure (Struct) via EDX, EAX two registers (same理: 32bit shaping In the 16bit environment via DX, AX delivery); other size structures returns to return their address by EAX; (so the return value type is not 1, 2, 4, 8byte, the efficiency may be relatively poor) In the parameter and return value transfer, the type of reference method can be regarded as the same way as the pass pointer; Float / Double (including delphi) is returned by floating point register ST (0); specific analysis See: http: //blog.9cbs.net/avaalonbbs/archive/2004/12/25/2293.aspx

::::: :::::::::::::::::::::: ::::::::::::::::::

Implicit link

This article is now not a specific instructions for implicit links, just make a probably introduction (next time you do a specific instruction). When the process runs, all related DLLs are loaded into memory, then map to the address of the process. Space, when a process is to call a lot of DLL, this method is particularly wasting memory, so it is best to use the display load when loading a lot of DLLs.

When the function is called in the DLL

To use the extern declaration to be external variables

For example, Extern Int Add (int Num1, int Num2);

But should also be noted that when compiling the DLL, put the compiled lib files in the directory of the execution file, and connect the lib file when compiling the execution file.

The function to be exported when writing the DLL is the function that can be called by the external program.

The general large project is developed in the development of the DLL, and the predefined declaration is

====================================== = 时候 导 时候 导 时候 导 就 在 在 在 在 在 在When the function is plus __DECLSPEC (DLLEXPORT), the C compiler is adapted to support the function name to support the function of the function. When the executable module executes the function, the name is not found, there will be an error in the call! When using externaln "c", you can tell the compiler that you don't have to modify the function name and variable name. This allows you to call this function with a C or C compiler program.

The above operation is only available to the executable module created by VC , if you use the module of the other compiler to call the DLL, you need some additional operations.

C Compile When compiling, the name will be adapted. When a function is used_stdcall (WinApi) calling rules, the MS compiler will adapt the name of the function.

For example: __ declspec (dllexport) long __stdcall proc (int A, int b);

The compiler will adapt to __proc @ 8

Therefore, when the function PROC in the DLL is called a non-C or non-C compiler, the function cannot be found.

This way we can define a DEF file to solve and add the following Exports in the DEF file:

Exports

PROC

DEF Module Performing Principle: When the connection program analyzes this DEF file, it finds that proc and __proc @ 8 are output, because the two functions are mutually matched, so the connection program uses PROC to output the function, do not use _ _Proc @ 8 to output function name

========================================

Below is the specific use of DEF

-------------------------------------------------- -------------------------------------------------- ---------------- Module definition file (.def) is a text file composed of one or more module statements used to describe the DLL attribute, each DEF file must contain at least The following module definition statement:

* The first statement must be a library statement, pointing out the name of the DLL;

* The exports statement lists the name of the exported function; the function to the function to be output is listed under Exports, this

A name must be exactly the same as the name of the definition function, so get a function name without any modification.

* Use the Description statement to describe the use of the DLL (optional); * ";" comment on a row (optional).

-------------------------------------------------- -------------------------------------------------- ------------------

///-DLLTEST.H

#ifdef dll1_api

#ELSE

#define dll1_api extern "c" _declspec (dllimport)

#ENDIF

DLL1_API INT _STDCALL ADD (Int A, INT B);

DLL1_API INT _STDCALL SUBTRACT (Int A, INT B);

//

////dllteest.cpp

#define DLL1_API EXTERN "C" _Declspec (DLLEXPORT)

#include "dll1.h"

#include

INT _STDCALL Add (Int A, INT B)

{

RETURN A B;

}

INT _STDCALL SUBTRACT (Int A, INT B)

{

Return A-B;

}

//

// DEF file

Library DLLTest

Exports

Add

Subtract

With the above files, you can call these functions in the place.

void cdlltestdlg :: Onbtnsubtract ()

{

// Todo: Add Your Control Notification Handler Code Here

CString Str;

Str.Format ("5-3 =% D", Subtract (5, 3));

MessageBox (STR);

}

Void cdlltestdlg :: onbtnoutput ()

{

// Todo: Add Your Control Notification Handler Code Here

Point Pt;

Pt.output (5, 3);

} The following detailed introduction shows loading

Load loading

The VC compiler will generate the name adaptation when compiling the DLL; mainly in a non-C environment, it is not possible to identify the function of the module file type DEF, which is mainly convenient for non-C programs to call the function in the DLL.

Then use the display to load, you must pay attention to the name of the name, because the name of the name is adapted after the name is adapted, so that the load will fail. However, it is possible to load: MSDN's second parameter in GetProAddress is described in this description of the pointer to a null-term, or the function's order value. That is to say that functions can be used The serial number is called to call the function. The specific method is procadd = (myProc) getProcAddress (Hinstlib, MakeintResource (i))); (i))); (i) the serial number in the DLL can be viewed with Dumpbin tools, but generally do not need this The way the serial number is used to get the address of the function, because this is very unintervision! Below you will use the module definition file (DEF) to avoid adaptation issues in the name of the function in the DLL.

Display load DLL

// MSDN Display loaded DEMO

USING RUN-TIME DYNAMIC LINKING

You can use the same DLL in both load-time and run-time dynamic linking. The following example uses the LoadLibrary function to get a handle to the Myputs DLL (see Creating a Simple Dynamic-Link Library). If LoadLibrary succeeds, the program uses the returned handle in the GetProcAddress function to get the address of the DLL's myPuts function. After calling the DLL function, the program calls the FreeLibrary function to unload the DLL.Because the program uses run-time dynamic linking, it is not necessary to Link The Module With an IMPORT LIBRARY for the DLL.

This example illustrates an important difference between run-time and load-time dynamic linking. If the DLL is not available, the application using load-time dynamic linking must simply terminate. The run-time dynamic linking example, however, can respond to the Error.

// a Simple Program That Uses LoadLibrary and

// GetProcaddress to access myputs from myputs.dll.

#include

#include

TYPEDEF INT (* MyProc) (LPTSTR);

Void main (void)

{

Hinstance hinstlib;

MyProc Procadd;

Bool ffreeresult, fruntimelinksuccess = false;

// Get a Handle to the DLL Module.

Hinstlib = loadingLibrary (Text ("DLLTEST"));

// if The Handle Is Valid, Try to Get The Function Address.

IF (Hinstlib! = NULL)

{

PROCADD = (MyProc) GetProcaddress (Hinstlib, Text ("Proc");

// if the function address is valid, call the function.

IF (NULL! = Procadd)

{

Fruntimelinksuccess = true;

(ProCADD) ("" "" ""

}

// free the dll module.

FFreeResult = freeElibrary (Hinstlib);

}

// if unable to call the dll function, use an alternative.

IF (! fruntimelinksuccess)

Printf ("Message Via Alternative Method / N");

For several functions of the above, some of the necessary descriptions:

LoadLibrary: Loads the specified DLL, the load method is to find in the current directory, if you find the re-environment variable directory;

Still watching the description of MSDN

............... ..

HModule LoadLibrary (

LPCTSTR LPFILENAME

);

Parameters

LPFileName

[In] Pointer to a null-terminated string that names the executable module (either a .dll or .exe file). The name specified is the file name of the module and is not related to the name stored in the library module itself, As specified by the library keyword in the module-definition (.def) file.

GetProcadDress: It is a function in known DLLs, returns the address of the specified function.

Description on MSDN

This Function Returns The Address of The Specified Exported DLL function.

FarProc getProcaddress

HModule HModule,

LPCWSTR LPPROCNAME

);

Parameters

HModule

Handle to The DLL Module That Contains the Function.

The loadLibrary or getModuleHandle Function Returns this handle.

LPPROCNAME

[out] Pointer to a null-terminated string containing the function name, or specific value.

IF this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.

The LPPROCNAME Parameter Must Be in Unicode.

REMARK:

.

.

. This is the sdk header files.

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

New Post(0)