Visual c ++ DLL programming implementation

Source: Internet
Author: User
Tags microsoft c

Visual c ++ DLL programming implementation

Since Microsoft launched a 16-bit Windows operating system, every version of Windows operating system is dependent on functions and data in the dynamic link library (DLL, in fact, almost all content in Windows is represented by DLL in one or another form, for example, the displayed fonts and icons are stored in the gdi dll, the Code required to display Windows desktops and process user input is stored in a user DLL, and a large number of APIs are required for Windows programming. the function is also included in the kernel DLL.

Using DLL in Windows has many advantages. The most important thing is that multiple applications, or even applications written in different languages, can share a DLL file, the real implementation of resource "sharing" greatly reduces the application code execution and makes more effective use of the memory; another advantage of using DLL files as a separate program module, encapsulation and independence are good. When the software needs to be upgraded, the developer only needs to modify the corresponding DLL file, and when the function in the DLL changes, as long as it is not a parameter change, the program code does not need to be re-compiled. This is very useful in programming and greatly improves the efficiency of software development and maintenance.

Since DLL is so important, it is a problem that programmers have to solve to find out what is DLL and how to develop and use it in windows. To address these problems, this article uses a simple example, that is, to implement the maximum and minimum integers in a DLL, it comprehensively parses the process of programming and implementing DLL in the Visual C ++ compiling environment. The program code used in this article is passed in the Windows98 system and Visual C ++ 6.0 compiling environment.

Ii. dll Concept

DLL is a library file that contains a number of functions, classes, or resources. functions and data are stored in a DLL (server) and exported by one or more customers. These customers can be applications or other DLL. The dll library is different from the static library. In the case of a static library, functions and data are compiled into a binary file (usually with the extension *. lib ), when processing program code, the visual C ++ compiler restores these functions and data from the static library and combines them with other modules in the application to generate executable files. This process is called "static link". In this case, because all the content required by the application is copied from the library, the static library itself does not need to be released together with the executable file.

In the case of a dynamic library, there are two files, one is imported into the database (. lib) file. One is a DLL file. The imported file contains the name and location of the function exported by the DLL. The dll contains the actual function and data, the application uses the Lib file to link to the required DLL file. The functions and data in the library are not copied to the executable file. Therefore, in the executable file of the application, stores not the called function code, but the memory address of the function to be called in the DLL, in this way, when one or more applications are running, the program code is linked to the called function code, thus saving memory resources. From the above description, we can see that the DLL and. Lib files must be released along with the application, otherwise the application will produce errors.

Microsoft's Visual C ++ supports three types of DLL: Non-mfc dll (non-MFC dynamic library), regular DLL (conventional DLL), and extension DLL (Extended DLL ). Non-mfc dll refers to a DLL written in C language without the use of the MFC class library structure. The exported function is a 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 using the MFC class library. One obvious feature of this DLL is that there is a class in the source file that inherits cwinapp (note: although such DLL is derived from cwinapp, there is no message loop ), the exported function is a C function, C ++ class, or C ++ member function (do not confuse the C ++ class with the Microsoft C ++ class of MFC ), applications that call conventional DLL do not need to be MFC applications, as long as they can call C-like functions, they can be used to develop applications in Visual C ++, dephi, Visual Basic, Borland C, and other compiling environments.

Conventional dll can be subdivided into static link to MFC and dynamic link to MFC. The differences between these two types of conventional DLL are described below. Compared with conventional DLL, extended DLL is used to export functions or subclasses that enhance the basic class of MFC. This type of dynamic link library can be used to output a class inherited from MFC.

The extension DLL is created using the dynamic link version of MFC, and is called only by applications written in the MFC class library. For example, you have created a derived class from the ctoolbar class of MFC to create a new toolbar. to export this class, you must put it in an extended DLL of MFC. Extension DLL is different from conventional DLL. It does not have a class Object inherited from cwinapp. Therefore, developers must add initialization code and end code to the dllmain function in the DLL.

3. Create a dynamic link library

In the Visual C ++ 6.0 development environment, open the filenewproject option, you can select Win32 dynamic-link library or MFC Appwizard [DLL] to create dynamic link libraries of different types such as non-mfc dll, regular DLL, and extension DLL in different ways.

1. Create a non-mfc dll dynamic link library using Win32 dynamic-Link Library

Each dll must have an entry point, which is the same as an application written in C. It must have a winmain function. In non-mfc dll, dllmain is a default entry function. You do not need to write your own DLL entry function, with this default entry function, the dynamic link library can be correctly initialized when called. If the application DLL needs to allocate additional memory or resources, or you need to initialize and clear each process or thread, you need. in the CPP file, the dllmain () function is written in the following format.

 

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

In the parameter, hmoudle is a handle that points to itself when the dynamic library is called (in fact, it is a selector pointing to the _ dgroup segment ); ul_reason_for_call indicates the reason why a dynamic library is called. When a process or thread loads or detaches a Dynamic Linked Library, the operating system calls the entry function, it also describes the reason why the dynamic link library is called. All its possible values are dll_process_attach: process called, dll_thread_attach: thread called, dll_process_detach: process stopped, dll_thread_detach: the thread is stopped; lpreserved is a reserved parameter. So far, the DLL entry function has been written, and the remaining implementation is not difficult. You can add the function or variable you want to output in the DLL project.

We already know that the DLL is a library file containing several functions. before using the functions in the DLL, the application should first export these functions for application use. There are two methods to export these functions. One is to use the export keyword _ declspec (dllexport) when defining the function, and the other is to use the module definition file when creating the DLL file. def. Note that the def file cannot be used when the first method is used. The following two examples illustrate how to use these two methods to create a DLL file.

1) Use the export function keyword _ declspec (dllexport) to create mydll. dll. There are two functions in the dynamic link library, which are used to obtain the maximum and minimum numbers of two numbers respectively. In the mydll. h and mydll. cpp files, enter the following original code:
 

// Mydll. h
Extern "C" _ declspec (dllexport) int max (int A, int B );
Extern "C" _ declspec (dllexport) int min (int A, int B );
// Mydll. cpp
# Include
# Include "mydll. H"
Int max (int A, int B)
{
If (A> = B) return;
Else
Return B;
}
Int min (int A, int B)
{
If (A> = B) return B;
Else
Return;
}

After the dynamic link library is compiled successfully, open the DEBUG directory in the mydll project and you can see the mydll. dll and mydll. Lib files. The LIB file contains the DLL file name and the function name in the DLL file. This lib file is only for the "Image File" of the DLL file, and in the DLL file, the length of the Lib file is much smaller. It is used for implicit link to the DLL file. Readers may have noticed the keyword "extern C" in mydll. H, which allows other programming languages to access the functions in your compiled DLL.

2) create a project mydll using the. Def File

To use. def file to create DLL. Delete mydll in the project created in the previous example first. h file, keep mydll. CPP and delete it in the file header # include mydll. H Statement, and add a text file to the project, named mydll. def, then add the following code to the file:

Library mydll
Exports
Max
Min

The library statement indicates that the def file belongs to the corresponding DLL. The exports statement lists the name of the function to be exported. We can add @ n after the export function in the. Def file, for example, Max @ 1, Min @ 2, to indicate the sequence number of the function to be exported. It can be used for explicit connection. After the DLL is compiled, open the DEBUG directory in the project, and you will also see the mydll. dll and mydll. Lib files.

2. MFC Appwizard [DLL] method to generate common/extended DLL

There are three methods to generate a DLL file in the MFC Appwizard [DLL]. When creating a DLL, select the method to create a DLL according to the actual situation. One is static link of conventional DLL to MFC, and the other is dynamic link of conventional DLL to MFC. The difference between the two is that the former uses the static Link Library of MFC, And the generated DLL file is long. This method is generally not used. The latter uses the dynamic link library of MFC, the length of the generated DLL file is small. All the functions output by the DLL that dynamically link to the MFC rule should start with the following statement:
 

Afx_manage_state (afxgetstaticmodulestate () // This statement is used to correctly switch the status of the MFC module.

The last one is the MFC extension DLL, which is used to establish the derived class of MFC. The DLL is called only by the application program compiled by the MFC class library. We have already introduced that extension DLLs is different from regular DLLs. It does not have a class Object inherited from cwinapp. The Compiler defaults to a DLL entry function dllmain () as the initialization of DLL, You can implement initialization in this function. The Code is as follows:
 

Bool winapi apientry dllmain (hinstance hinstdll, DWORD reason, lpvoid flmpload)
{
Switch (reason)
{
.......... // Initialization code;
}
Return true;
}

The hinstdll parameter stores the DLL handle. The reason parameter specifies the reason for calling the function. lpreserved is a parameter reserved by the system. The implicit link is a non-zero value, and the explicit link value is zero.

When a DLL file is created under MFC, the def file framework will be automatically generated. Other files are no different from the traditional non-mfc dll, as long as the keyword _ declspec (dllexport) is written into the corresponding header file) function Type and function name, or enter the function name under exports in the generated def file. Note that when distributing the MFC extension DLL to other developers, do not forget to provide the header file describing the class in the DLL and the corresponding. the LIB file and DLL itself, and developers will be able to make full use of your developed extended DLL.

4. Dynamic Link Library DLL Link

Applications can use DLL in two ways: implicit link and explicit link. Before using the DLL, you must first know the structure information of the function in the DLL. Visual c ++ 6.0 stores a small program named dumpbin.exe in the VC indirectory, which can be used to view the function structure in the DLL file. In addition, the Windows system will follow the search order below to locate the DLL: 1. directory that contains the EXE file, 2. current working directory of the Process, 3. windows Directory, 4. windows Directory, 5. A series of directories listed in the PATH environment variable.

1. implicit link

The implicit link loads the DLL file into the application when the program starts execution. It is easy to implement implicit links. You only need to write the name of the imported function keyword _ declspec (dllimport) to the corresponding header file of the application. The following example uses an implicit link to call the min function in the mydll. dll library. First, generate a project named testdll and enter the following code in the dlltest. h and dlltest. cpp files:

 

// Dlltest. h
# Pragma comment (Lib, "mydll. lib ")
Extern "C" _ declspec (dllimport) int max (int A, int B );
Extern "C" _ declspec (dllimport) int min (int A, int B );
// Testdll. cpp
# Include
# Include "dlltest. H"
Void main ()
{Int;
A = min (8, 10)
Printf ("compare result % d", );
}
 

Before creating the dlltest.exe file, copy mydll. dll and mydll. lib to the directory where the current project is located, or copy it to the Windows System directory. If the DLL uses the def file, delete the keyword extern "c" in the testdll. h file ". Testdll. the keyword progam commit in the hfile is linked to mydll when the compiler of Visual C + is linked. lib file, of course, developers can also not use # pragma comment (Lib, "mydll. lib "), and enter mydll directly in the object/moduls column of the Setting-> link page of the project. lib is supported.

2. explicit link

Explicit links allow applications to load DLL files or uninstall DLL files at any time during execution, which is not implemented by implicit links. Therefore, explicit links provide better flexibility, it is more suitable for explanatory languages. However, implementing explicit links requires a little effort. In the application, call the dynamic link library provided by loadlibrary or the afxloadlibrary provided by MFC explicitly. The file name of the Dynamic Link Library is the parameter of the above two functions, and then use getprocaddress () obtain the function to be introduced. Since then, you can call the introduced function like using a function defined in the application. Before exiting the application, use the afxfreelibrary provided by freelibrary or MFC to release the dynamic link library. The following is an example of calling the max function in DLL through an explicit link.
 

# Include
# Include
Void main (void)
{
Typedef int (* Pmax) (int A, int B );
Typedef int (* pmin) (int A, int B );
Hinstance hdll;
Pmax Max
Hdll = loadlibrary ("mydll. dll"); // load the dynamic link library mydll. dll file;
Max = (Pmax) getprocaddress (hdll, "Max ");
A = max (5, 8 );
Printf ("compare result % d", );
Freelibrary (hdll); // uninstall the mydll. dll file;
}

In the above example, use the type definition keyword typedef to define the pointer to the same function prototype as the DLL, and then use loadlibray () load the DLL to the current application and return the handle of the current DLL file. Then, use the getprocaddress () function to obtain the function pointer imported to the application. After the function is called, use freelibrary () to uninstall the DLL file. Before compiling a program, copy the DLL file to the project directory or the Windows System directory.

When you use an explicit link to compile an application, you do not need to use the corresponding lib file. In addition, when using the getprocaddress () function, you can use the makeintresource () function to directly use the sequence number in the DLL function, for example, change getprocaddress (hdll, "min") to getprocaddress (hdll, makeintresource (2) (the sequential number of the function min () in the DLL is 2). In this way, the call speed of the function in the DLL is very fast, but remember the sequence number used by the function. Otherwise, an error occurs.
 
 

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.