Introduction to DLL in C ++ (details)

Source: Internet
Author: User
Tags types of functions
References: C ++ dynamic link library (DLL) programming VC ++ dynamic link library programming reader feedback and replies

From: http://blog.sina.com.cn/u/56cacf83010005an

Large applications are composed of many modules that complete relatively independent functions and collaborate with each other to complete the work of the entire software system. Some modules may have common functions and will still be used when constructing other software systems. When constructing a software system, if the source code of all modules is statically compiled into the entire application EXE file, some problems will occur: one drawback is that the size of the application is increased, it occupies more disk space and consumes a large amount of memory space during program running, resulting in a waste of system resources. Another drawback is that when writing large EXE programs, all source code must be adjusted during each modification and reconstruction, which increases the complexity of the compilation process and is not conducive to periodic unit tests.

Windows provides a completely different and effective programming and running environment. You can create an independent program module as a smaller DLL (Dynamic linkable Library) file, they can be compiled and tested separately. During runtime, the system will load the EXE program to the memory space only when it does need to call these DLL modules. This method not only reduces the size of the EXE file and the need for memory space, but also enables these DLL modules to be used by multiple applications at the same time. Windows itself implements some major system functions in the form of DLL modules.

In general, a DLL is a disk file. dll,. DRV,. Fon,. sys, and many system files with. EXE extension can be DLL. It consists of global data, service functions, and resources, and is loaded into the virtual space of the calling process by the system at runtime, becoming part of the calling process. If there is no conflict with other DLL, the file is usually mapped to the same address of the virtual space of the process. The DLL module contains various export functions to provide external services. A dll can have its own data segment but does not have its own stack. It uses the same stack mode as the application that calls it. a dll has only one instance in the memory; DLL implements code encapsulation.
The compilation has nothing to do with the specific programming language and compiler.

In the Win32 environment, each process copies its own read/write global variables. To share memory with other processes, you must use a memory ing file or declare a shared data segment. The stack memory required by the DLL module is allocated from the stack of the running process. When Windows loads the DLL module, it matches the process function call with the export function of the DLL file. In Windows, the DLL operation only maps the DLL to the virtual address space of the process that requires it. Any object (including variables) created by the code in the DLL function is owned by the thread or process that calls it.

Call Method

1. Static call method: the compilation system loads the DLL and the encoding of the DLL uninstallation when the application ends (if other programs use the DLL, in Windows, the Application Record of the DLL is reduced by 1 until all related programs end to use the DLL. It is simple and practical, but not flexible enough to meet general requirements.

Implicit call: You need to add the. Lib file generated when a dynamic Connection Library is generated to the project of the application. To use a function in the DLL, you only need to describe it. You do not need to call loadlibrary () and freelibrary () for implicit calls (). When a programmer creates a DLL file, the link program automatically generates a corresponding lib import file. This file contains the symbolic name and optional Identification Number of each DLL export function, but does not contain the actual code. The LIB file is compiled into the application project as an alternative DLL file.

When programmers compile and generate an application through static links, the calling functions in the application match the exported symbols in the Lib file. These symbols or identifiers enter the generated EXE file. The LIB file also contains the corresponding DL l file name (but not the full path name). The link program stores the name in the EXE file.

When a DLL file needs to be loaded while the application is running, Windows will find and load the DLL based on the information, and then use the symbolic name or identification number to achieve dynamic links to the DLL function. All DLL files called by the application will be loaded into the memory when the application EXE file is loaded. The executable program is linked to an input library file (. Lib file) that contains DLL output function information ). The operating system loads the DLL when using an executable program. The executable program calls the DLL output function directly through the function name. The Calling method is the same as its function in the program.

2. Dynamic calling method: the programmer uses API functions to load and uninstall the DLL to call the DLL. It is complicated to use, but can use the memory more effectively, is an important way to compile large-scale applications.

Explicit call: explicitly calls your dynamic Connection Library in the application using the afxloadlibrary provided by loadlibrary or MFC, the file name of the dynamic Connection Library is the parameter of the above two functions, and then getprocaddress () is used to obtain the function to be introduced. Since then, you can call the introduced function like a function defined by the application. Before exiting the application, use the afxfreelibrary provided by freelibrary or MFC to release the dynamic Connection Library. Directly call the loadlibary function of Win32 and specify the dll path as the parameter. Loadlibary
The hinstance parameter is returned. The application uses this parameter when calling the getprocaddress function. The getprocaddress function converts the symbolic name or identification number to the internal address of the DLL. The programmer can decide when to load or not load the DLL file, and the explicit link decides which DLL file to load at runtime. Before using the DLL program, you must load (loadlibrary) the DLL to obtain the handle of a DLL module. Then, call the getprocaddress function to obtain the pointer of the output function, you must uninstall the DLL (freelibrary) before exiting ).

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

DLL in MFC

  • Non-mfc dll: Refers to a DLL written directly in C language without the use of the MFC class library structure. The output function generally uses the Standard C interface, it can be called by applications not compiled by MFC or MFC.
  • Regular DLL: similar to the following extension DLLs, it is written in the MFC class library. Obviously, there is a class that inherits cwinapp in the source file. It can be subdivided into static connection to MFC and dynamic connection to MFC.

    The dynamic connection library for static connection to MFC is only supported by the Professional Edition and Enterprise Edition of VC. The output functions in such DLL applications can be used by any Win32 program, including the applications using MFC. The input function is in the following format:

    Extern "C" Export yourexportedfunction ();

    Without the extern "C" modifier, the output function can only be called from the C ++ code.

    DLL applications are derived from cwinapp, but there is no message loop.

    The output function in the DLL application that dynamically links to the MFC rule can be used by any Win32 program, including the application that uses the MFC. However, 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.

    Regular dll can be called by all applications written in languages that support DLL technology. In this dynamic connection library, it must have a class inherited from cwinapp. The dllmain function is provided by MFC and does not need to be explicitly written by itself.

  • Extension DLL: Used to reuse the classes inherited from MFC. That is to say, a dynamic Connection Library of this type can be used to output a class inherited from MFC. Its output functions can only be used by applications that use MFC and dynamically link to MFC. 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. Extension DLL is created using the dynamic connection version of MFC, and is called only by applications written in the MFC class library. Extension DLLs
    Unlike regular DLLs, it does not inherit class objects from cwinapp. Therefore, you must add initialization code and end code for your own dllmain 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.

    DLL entry function

    1. Each dll must have an entry point. dllmain is a default entry function. Dllmain is responsible for initialization and termination. Whenever a new process or a new thread of the Process accesses the DLL, or every process or thread accessing the DLL no longer uses or ends, all call dllmain. However, using terminateprocess or terminatethread to end a process or thread does not call dllmain.

    Dllmain function prototype:

    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;
      }
    }

    Parameters:

    Hmoudle: A handle that points to itself when the dynamic library is called (in fact, it is an selector pointing to the _ dgroup segment );

    Ul_reason_for_call: indicates the reason why the dynamic library is called. When a process or thread loads or unmounts a dynamic Connection Library, the operating system calls the entry function and describes the reason why the dynamic Connection Library is called. 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: a parameter reserved by the system;

    2. _ dllmaincrtstartup

    To use the dll version (multithreading) of the "c" Runtime Library (CRT, C run time Library), a DLL application must specify _ dllmaincrtstartup as the entry function, the DLL initialization function must be dllmain.

    _ Dllmaincrtstartup: Data (C Runtime data) of the "c" RunTime when the process or thread is bound to the DLL) allocate space and initialize and construct a global "C ++" object. When the process or thread terminates the use of DLL (detach), clear the C Runtime data and destroy the global "C ++" object. It also calls the dllmain and rawdllmain functions.

Rawdllmain is required when the DLL application dynamically links to the mfc dll, but it is statically linked to the DLL application. Explains the cause of status management.

Call conventions

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. It is the default MFC call convention.

3. The _ fastcall call convention is "people" 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. The Naked call uses the 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/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)

"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 a "@" symbol and the number of bytes of the parameter, in the format of _ functionname @ number.

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

_ Fastcall: Add a "@" symbol before the output function name, followed by a "@" 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 "? "Mark the 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, except that the start identifier of the parameter table changes from "@ YG" to "@ Yi ".

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

DLL Functions

The dynamic link library defines two types of functions: the export function and the internal function ). Export functions can be called by other modules. Internal functions are used within the DLL program that defines them.

The following methods are used to output functions:

1. Traditional Methods

Specify the function or variable to be input in the export section of the module definition file. The syntax format is as follows:

entryname[=internalname] [@ordinal[NONAME]] [DATA] [PRIVATE]

Where:

Entryname is the name of the output function or data to be referenced;

Internalname is the same as entryname;

@ Ordinal indicates the sequence number (INDEX) in the output table );

Noname is used only when output by sequence number (entryname is not used );

Data indicates that a data item is output. The program that outputs data using DLL must declare this data item as _ declspec (dllimport ).

In the preceding items, only entryname is required, and other items can be omitted.

For a "C" function, entryname can be equivalent to the function name, but for a "C ++" function (member function, non-member function), entryname is a modifier name. You can get the modified name of the function to be output from the. map image file, or use dumpbin/symbols to get the modified name, and then write them in the output module of the. Def file. Dumpbin is a tool provided by VC.

If you want to output a "C ++" class, write the data to be output and the modifier of the members to the. Def module definition file.

2. Output in the command line

Specify the/Export command line parameter for the link program Link and output the relevant functions.

3. Use the modifier _ declspec (dllexport) provided by MFC)

Add the _ declspec (dllexport) modifier before the declaration of the functions, classes, and data to be output to indicate the output. _ Declspec (dllexport) removes the underline prefix of the output function name in the case of C call conventions and C compilation. Extern "C" makes it possible to use the C Compilation Method in C ++. To define a "C" function under "C ++", you need to add the extern "C" keyword. Use extern "c" to indicate that the function uses the C compiling method. The output "C" function can be called from the "c" code.

For example, a C ++ file contains the following functions:

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.

Module definition file (. Def)

The module definition file (. Def) is a text file consisting of one or more module statements used to describe the DLL attributes. Each def file must contain at least the following module definition statements:

  • The first statement must be a library statement that specifies the DLL name;
  • The exports statement lists the names of the exported functions. The modified names of the functions to be output are listed under exports. The names must be exactly the same as those of the defined functions, in this way, a function name without any modification is obtained.
  • You can use the description statement to describe the usage of the DLL (optional );
  • ";" (Optional) Comment on a row ). The relationship between the DLL program and the program that calls its output function

    1. Relationship between DLL and process and thread

  • The DLL module is mapped to the virtual address space of the process that calls it.
  • The dll Memory is allocated from the virtual address space of the calling process and can only be accessed by the thread of the process.
  • The DLL handle can be used by the calling process, and the call Process Handle can be used by the DLL.
  • DLL uses the stack of the calling process.

    2. About shared data segments

    The global variables defined by dll can be accessed by the calling process; The dll can access the global data of the calling process. Each process using the same dll has its own DLL global variable instance. If multiple threads concurrently access the same variable, you need to use the synchronization mechanism. For a DLL variable, If you want each thread that uses the DLL to have its own value, the local thread storage should be used (TLS, Thread Local strorage ).

    You can add pre-compiled commands to a program or set the data segment attributes in the project settings of the development environment. these variables must be assigned with initial values. Otherwise, the compiler will place the variables without initial values in a data segment called uninitialized.

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.