MFC-MFC DLL

Source: Internet
Author: User

  1. MFC DLL

     

    Generally, there is a lot of knowledge about DLL in the introduction to Windows programming, while the introduction to MFC is rarely mentioned. Even if you use MFC to write a dynamic link library, it is necessary for programmers who are initially familiar with DLL to understand the background of DLL. In addition, MFC provides a new way to help write DLL programs. Therefore, this section briefly introduces related concepts.

     

  2. DLL background

     

  1. Static and Dynamic Links

     

If the target code (. obj) of the current link references a function but does not define it, the linked program may solve this reference to the function from the outside in two ways:

  • Static Link

     

. The linked Program maintains all references to the function, so that they point to the place where the program now contains the copy of the function.

  • Dynamic Link

     

The linked program also searches for one or more library files (input library. lib). When the input record of the referenced function is found in a database, the input record is copied to the result executable file to generate a dynamic link to the function. Here, the input record does not contain the code or data of the function, but specifies a dynamic link library containing the Code of the function and the sequence number or function name of the function.

When the program runs, Windows loads the program and looks for any dynamic links in the file. For each dynamic link, Windows loads the specified DLL and maps it to the virtual address space of the calling process (if there is no ing ). Therefore, the actual link between the call and the target function is not completed once (static) when the application is linked. On the contrary, it is completed by Windows (dynamic) when the program is run ).

This kind of dynamic link is called dynamic link during loading. There is also a dynamic link method that will be discussed below.

  1. Dynamic Link Method

     

The method for linking functions in the dynamic link library is as follows:

  • Dynamic Link during loading (Load_time dynamic linking)

     

As described above. Windows searches for the DLL to be loaded in the following order:

 

Application directory → current directory → Windows SYSTEM directory → Windows Directory → PATH specified by PATH environment variable.

 

  • Dynamic Link during runtime (Run_time dynamic linking)

     

The programmer uses LoadLibrary to load the DLL into the memory and map the DLL to the virtual address space of the calling process (if the ing has been made, the reference count of the DLL will be increased ). First, LoadLibrary searches for DLL, And the search sequence is the same as the dynamic link when loading. Then, use GetProcessAddress to get the address of the output function in the DLL and call it. Finally, FreeLibrary is used to reduce the DLL reference count. When the reference count is 0, the DLL module is removed from the virtual space of the current process.

 

  1. Input Library (. lib ):

     

    The input library uses. lib as the extension. The format is COFF (Common object file format ). The extension of the COFF standard library (static Link Library) is also. lib. You can use dumpbin to view COFF Files.

     

    The input library contains the dynamic link information of the output function or output data in the DLL. When you use MFC to create a DLL program, the input Library (. lib) and dynamic link library (. dll) are generated ).

     

  2. Output file (. exp)

     

    The output file uses the. exp extension and contains information about the output functions and data. The linked program uses it to create a DLL dynamic link library.

     

  3. Image file (. map)

     

    The image file with the. map extension contains the following information:

     

    Module name, timestamp, and group list (each group contains the starting address, length, group name, and class name in the form of section: offset), public symbol list (in the form of section: offset address, symbol name, virtual address flat address, defining the symbol. obj file), entry points such as section: offset, fixup list.

     

  4. Lib.exe Tool

     

    It can be used to create input databases and output files. Normally, lib.exe is used. If the project target is to create a DLL program, the linked program will complete the creation of the input library.

     

    For more information, see the MFC user manual and documentation.

     

  5. Linkage Specification)

     

    This is the connection protocol for functions or Procedure written in different programming languages. The connection specifications supported by MFC are "C" and "C ++", and the default is "C ++". If you want to declare a function or variable linked to "C, the following syntax is generally used:

     

    # If defined (_ cplusplus)

    Extern "C"

    {

    # Endif

    // Function declaration)

     

    ...

    // Variable Declaration (variables declarations)

     

    # If defined (_ cplusplus)

    }

    # Endif

    All C standard header files are declared using the above syntax, so that they can be used in the C ++ environment.

     

  6. 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.

    1. Call conventions

       

The call convention (Calling convention) determines the order in which function parameters are pushed to the stack. The caller or the caller pushes the parameter to the stack and generates the function modifier name. MFC supports the following call conventions:

 

  1. _ Cdecl

     

    The parameter is pushed from right to left to the stack. The caller pushes the parameter to the stack. For a "C" function or variable, the modifier name is underlined before the function name. The "C ++" function is different.

     

    For example, the modified name of function void test (void) is _ test. For a global function that does not belong to a class, what is the modified name? Test @ ZAXXZ.

     

    This is the default MFC call convention. Because the caller is responsible for popping up the parameter stack, you can define a variable number of parameters for the function, such as the printf function.

     

  2. _ Stdcall

     

    The parameter is pushed from right to left to the stack. The parameter is pushed to the stack by the caller. For a "C" function or variable, the modifier name is prefixed with the following line, followed by the function name, followed by the symbol "@" and the number of bytes of the parameter, such as the function int func (int, double B) the modifier is _ func @ 12. The "C ++" function is different.

     

    All Win32 API functions follow this convention.

     

  3. _ Fastcall

     

    The first two DWORD types or parameters that occupy less bytes are put into the ECX and EDX registers, and the remaining parameters are pushed to the stack in the order from right to left. The called calls bring up the parameter stack. For "C" functions or variables, the modifier name is prefixed with "@" and then the function name, the symbol "@" and the number of bytes of the parameter are followed. For example, the modifier of the int func (int a, double B) function is @ func @ 12. The "C ++" function is different.

     

    In the future, compilers may use different registers to store parameters.

  4. Thiscall

     

    Applies only 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

     

    1-4 call timing. If necessary, when entering the function, the compiler will generate code to save the ESI, EDI, EBX, and EBP registers, 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 with _ declspec as follows:

     

    _ Declspec (naked) int func (formal_parameters)

    {

    // Function body

    }

  6. Outdated call conventions

     

Some original call conventions can no longer be used. They are defined as call conventions _ stdcall or _ cdecl. For example:

# Define CALLBACK _ stdcall

# Define WINAPI _ stdcall

# Define WINAPIV _ cdecl

# Define APIENTRY WINAPI

# Define APIPRIVATE _ stdcall

# Define PASCAL _ stdcall

Table 7-1 shows the modified names of a function under several call conventions (the "C ++" function in the table refers to the "C ++" global function, not a member function ), the function prototype is void CALLTYPE test (void). CALLTYPE can be _ cdecl, _ fastcall, and _ stdcall.

 

Table 7-1 modifier names under different call conventions

 

Call conventions

 

Extern "C" or. C file

 

. Cpp,. cxx or/TP compilation Switch

 

_ Cdecl

 

_ Test

 

? Test @ ZAXXZ

 

_ Fastcall

 

@ Test @ 0

 

? Test @ YIXXZ

 

_ Stdcall

 

_ Test @ 0

 

? Test @ YGXXZ

 

 

      1. DLL application type of MFC

         

  1. Static link to the MFC rule DLL Application

     

    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.

     

  2. Dynamic Link to the MFC rule DLL Application

     

    The output functions in such DLL applications can be used by any Win32 program, including the applications using 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. For more information about the module status of MFC, see Chapter 9th.

     

    Other aspects are the same as those of the Rule DLL application that is statically linked to MFC.

     

  3. Extend the DLL Application

     

This type of DLL application dynamically links to MFC. The function output can only be used by the application that uses MFC and dynamically links to MFC. Compared with rule DLL:

  1. It does not have an object derived from CWinApp;

     

  2. It must have a DllMain function;

     

  3. DllMain calls the AfxInitExtensionModule function and must check the return value of this function. If 0 is returned, DllMmain also returns 0;

     

  4. If you want to output CRuntimeClass objects or Resources, 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 that uses extended DLL must have a class derived from CWinApp, and the initialization function of extended DLL is generally called in InitInstance.

     

The reason for this and the specific code form are described in section 9.4.2.

The MFC class library is also provided in the form of DLL. The DLL that dynamically links to MFC usually refers to the MFCXX. DLL or MFCXXD. DLL that implements the core functions of MFC (XX indicates the version number and XXD indicates the debugging version ). The DLL that provides OLE (MFCOXXD. DLL or MFCOXX0.DLL) and NET (MFCNXXD. DLL or MFCNXX. DLL) services is the extension DLL that dynamically links to the MFC core DLL.

 

In fact, MFCXX. DLL can be considered as a special case of extended DLL because it also has the above features of extended DLL.

 

    1. DLL description

       

  1. The DLL application entry point is DllMain.

     

    For programmers, the DLL application entry point is DllMain.

     

    DllMain is responsible for Initialization and Termination. Whenever a new process or a new thread of the Process accesses the DLL, or when every process or thread accessing the DLL no longer uses the DLL or ends, it will call DllMain. However, using TerminateProcess or TerminateThread to end a process or thread does not call DllMain.

     

    The DllMain function prototype meets the requirements of DllEntryPoint and has the following structure:

     

    Bool winapi DllMain (HANDLE hInst,

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

    }

    Where:

    Parameter 1 is the module handle;

     

    Parameter 2 refers to the class for calling DllMain. Four values are as follows: the new process needs to access the DLL; the new thread needs to access the DLL; a process no longer uses the DLL (Detach from DLL ); A thread no longer uses DLL (Detach from DLL ).

     

    Parameter 3 is retained.

     

    If the programmer does not specify DllMain, the compiler uses its own DllMain. This function only returns TRUE.

     

    The rule DLL application uses the DllMain of MFC, which calls the InitInstance function and ExitInstance function of the DLL Application Object (derived from CWinApp.

     

    The extension DLL must implement its own DllMain.

     

  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.

     

  3. DLL functions and data

     

    DLL functions are divided into two types: Output Functions and internal functions. Output functions can be called by other modules. Internal functions are used within the DLL program that defines them.

     

    Although the DLL can output data, the data of the common DLL program is only for internal use.

     

  4. The relationship between the DLL program and the program that calls its output function

     

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.

 

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 ).

 

    1. Method of output function

       

  1. Traditional Method

     

    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. For a "C ++" function (member function or 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 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 function, class, and data to indicate the output. MFC provides some macros for this purpose, as shown in table 7-2.

 

Table 7-2 input/output modifiers defined by MFC

 

Macro name

Macro content

 

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

 

AFX_EXT_DATADEF

 

 

 

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.

To define the "C" function under "C ++", add the extern "C" keyword. The output "C" function can be called from the "C" code.

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.