VC Program in WIN32 Environment Dynamic link library (DLL) programming principle _c language

Source: Internet
Author: User
Tags win32

This paper describes in detail the VC program in the WIN32 Environment Dynamic link library (DLL) programming principle. Share to everyone for your reference. The specific analysis is as follows:

Generally larger applications are composed of a number of modules, these modules to complete the relatively independent functions, they collaborate with each other to complete the work of the entire software system. There may be some modules that are more versatile and will still be used when constructing other software systems. When constructing a software system, if the source code of all the modules are statically compiled into the entire application EXE file, there will be some problems: one drawback is that the size of the application, it will occupy more disk space, the program will also consume a large memory space, resulting in the waste of system resources; Another drawback is that In the preparation of large EXE program, every time you modify the rebuild must adjust the compilation of all source code, increase the complexity of the compilation process, but also not conducive to phased unit testing.

A completely different, more efficient programming and running environment is available on the Windows System platform, and you can create stand-alone program modules as smaller DLLs (Dynamic linkable Library) files and compile and test them separately. At run time, the system will load them into the memory space only if the EXE program is sure to call these DLL modules. This approach not only reduces the size of the EXE file and the need for memory space, but also makes these DLL modules can be used by multiple applications at the same time. Microsoft Windows itself implements some of the major system features in the form of DLL modules. For example, some basic functions in IE are implemented by DLL files, which can be invoked and integrated by other applications.

In general, a DLL is a disk file (usually with a DLL extension) that consists of global data, service functions, and resources, which are loaded into the virtual space of the process by the system at run time and become part of the calling process. If there is no conflict with other DLLs, the file is typically mapped to the same address on the process virtual space. DLL modules contain various export functions to provide services to the outside world. Windows matches the process function call to the exported function of the DLL file when the DLL module is loaded.

In a WIN32 environment, each process replicates its own read/write global variables. If you want to share memory with other processes, you must use a memory-mapped file or declare a shared data segment. The stack memory required by the DLL module is allocated from the stack of the running process.
DLLs are now becoming easier to write. Win32 has greatly simplified its programming model and has many support from the AppWizard and MFC class libraries.

Matching of export and import functions

DLL file contains a table of exported functions. These export functions are associated with the outside world by their symbolic names and integers called identification numbers. The function table also contains the address of the function in the DLL. When an application loads a DLL module, it does not know the actual address of the calling function, but it knows the symbol name and identification number of the function. Dynamic link processes dynamically establish a corresponding table of function calls and function addresses when loading DLL modules. If you recompile and rebuild the DLL file, you do not need to modify the application unless you change the symbolic name and sequence of parameters of the exported function.
Simple DLL files provide export functions only for applications, and more complex DLL files call functions in other DLL files in addition to the exported functions. In this way, a special DLL can have both the import function and the import function. This is not a problem, because the dynamic link process can handle cross related situations.
In your DLL code, you must explicitly declare the exported function as follows:

Copy Code code as follows:
__declspec (dllexport) int myfunction (int n);

However, you can also list the exported functions in the module definition (DEF) file, but doing so often causes more trouble. In the application context, it is required to explicitly declare the appropriate input function as follows:
Copy Code code as follows:
__declspec (dllimport) int myfuncition (int n);

Import and export declarations alone cannot link function calls within an application to the appropriate DLL file. The application's project must specify the required input library (LIB file) for the linker. And the application must, in fact, contain at least one call to a DLL function.

Second, with the DLL module to establish links

There are two ways to link an application import function to an exported function in a DLL file: implicit linking and explicit linking. Implicit linking refers to the fact that the actual storage path of the DLL file is not required in the application, and the programmer does not need to care about the actual load of the DLL file. An explicit link is the opposite of this.
Implicit linking means that when a programmer creates a DLL file, the linker automatically generates a corresponding LIB import file. The file contains the symbol name and optional identification number of each DLL export function, but does not contain actual code. The Lib file is compiled into the application project as an alternate file for the DLL. When the programmer compiles the build application through static linking, the calling functions in the application match the exported symbols in the Lib file, which enter into the generated EXE file. The Lib file also contains the corresponding DLL file name (but not the full pathname), which the linker stores inside the EXE file. When you need to load a DLL file while the application is running, Windows discovers and loads the DLL based on that information, and then implements dynamic links to DLL functions by symbol name or identification number.
Explicit linking is more appropriate for integrated development languages such as VB. With explicit links, programmers do not have to use the import file, they call the Win32 loadlibary function directly, and specify the path of the DLL as a parameter. Loadlibary returns the HINSTANCE parameter that the application uses when calling the GetProcAddress function. The GetProcAddress function converts a symbol name or an identification number to an address within the DLL. Suppose you have a DLL file that exports the following functions:

Copy Code code as follows:
extern "C" __declspec (dllexport) double squareroot (double D);

The following is an example of an application's explicit link to the exported function:
Copy Code code as follows:
typedef double (SQRTPROC) (double);
HINSTANCE hinstance;
sqrtproc* pfunction;
VERIFY (Hinstance=::loadlibrary ("C://winnt//system32//mydll.dll"));
VERIFY (pfunction= (sqrtproc*):: GetProcAddress (HInstance, "squareroot"));
Double d= (*pfunction) (81.0);//Call the DLL function

In implicit linking, all DLL files invoked by the application are loaded into memory when the application EXE is loaded, but if explicit linking is used, programmers can determine when the DLL file is loaded or not loaded. An explicit link determines which DLL file to load at run time. For example, you can load a DLL module with a string resource in English and the other in Spanish. The application loads the corresponding DLL file after the user chooses the appropriate language.

Third, the use of symbolic name link and identification Number link

In a Win16 environment, symbolic name links are inefficient, and all of the time identification links are the primary way of linking. In the WIN32 environment, the efficiency of symbolic name links has been improved. Microsoft now recommends using symbolic name links. However, the DLL version in the MFC library still uses an identification Number link. A typical MFC program may be linked to hundreds of MFC DLL functions. The exe file body of an application with an identification Number link is relatively small because it does not have to contain the long string symbol name of the import function.

Iv. Writing DllMain functions

The DllMain function is the default entry point for DLL modules. This function is called when Windows loads a DLL module. The system first calls the global object's constructor, and then calls the global function DllMain. The DllMain function is invoked not only when the DLL link is loaded into the process, but also when the DLL module is detached from the process (and at other times). The following is an example of a framework DllMain function.

Copy Code code as follows:
HINSTANCE g_hinstance;
extern "C" int apientry DllMain (hinstance hinstance,dword dwreason,lpvoid lpreserved)
{
if (Dwreason==dll_process_attach)
{
TRACE0 ("ex22a.") DLL initializing!/n ");
This is where you initialize the
}
else if (Dwreason=dll_process_detach)
{
TRACE0 ("ex22a.") DLL terminating!/n ");
To do cleanup work here
}
Return 1;//Successful
}

If the programmer does not write a DllMain function for the DLL module, the system introduces a default DllMain function version from the other runtime that does nothing. The DllMain function is also invoked when a single thread starts and terminates. As indicated by the Dwreason parameter.

Five, module handle

Each DLL module in the process is identified by a globally unique 32-byte hinstance handle. The process itself also has a hinstance handle. All of these module handles are valid only within a particular process, and they represent the starting address of the DLL or EXE module in the process virtual space. In Win32, the values of hinstance and hmodule are the same, and the two types can be substituted for use. The process module handle is almost always equal to 0x400000, and the default handle to the loaded address of the DLL module is 0x10000000. If the program uses several DLL modules at the same time, each will have a different hinstance value. This is because a different base address was specified when the DLL file was created, or because the loader relocated the DLL code.
Module handles are particularly important for loading resources. The Win32 FindResource function contains a hinstance parameter. Both EXE and DLL have their own resources. If the application requires resources from a DLL, this parameter is specified as a module handle to the DLL. If you want the resources contained in the EXE file, specify the module handle for the EXE.
But there is a problem before using these handles, how do you get them? If you need to get the EXE module handle, call the WIN32 function with the null parameter GetModuleHandle, and if you need a DLL module handle, call the Win32 function GetModuleHandle with the DLL file name as the parameter.

Vi. How the application finds DLL files

If your application uses LoadLibrary explicit linking, you can specify the full path to the DLL file in the parameters of this function. If you do not specify a path, or if you make an implicit link, Windows locates the DLL in the following search order:

1. A directory containing EXE files,
2. The current working directory of the process,
3. Windows system directory,
4. Windows directory,
5. A series of directories listed in the PATH environment variable.

Here is a trap that is prone to mistakes. If you use VC + + for project development, and specifically create a project for the DLL module, then copy the generated DLL file to the system directory and invoke the DLL module from the application. So far, everything is fine. Then you make some modifications to the DLL module and regenerate the new DLL file, but you forget to copy the new DLL file to the system directory. The next time you run the application, it still loads the old version of the DLL file, so be careful!

VII. Debugging DLL Programs

Microsoft's VC + + is an effective tool for developing and testing DLLs by simply running the debugger from a DLL project. When you do this for the first time, the debugger asks you for the path to the exe file. The debugger automatically loads the DLL each time it is run in the debugger. The exe file then discovers the DLL file with the search sequence above, which means you must set the PATH environment variable to include the disk path to the DLL file, or you can copy the DLL file to the directory path in the search sequence.

I hope this article on the VC program for everyone to help.

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.