DYNAMIC-LINK LIBRARY


'Dynamic-link library' (also written without the hyphen), or 'DLL', is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV (for legacy system drivers).
The file formats for DLLs are the same as for Windows EXE files — that is, Portable Executable (PE) for 32-bit Windows, and New Executable (NE) for 16-bit Windows. As with EXEs, DLLs can contain code, data, and resources, in any combination.
In the broader sense of the term, any data file with the same file format can be called a ''resource DLL''. Examples of such DLLs include ''icon libraries'', sometimes having the extension ICL, and font files, having the extensions FON and FOT.

Contents
Background
Features
Memory management
Import libraries
Symbol resolution and binding
Explicit run-time linking
Compiler and language considerations
In the heading of a source file, the keyword library is used instead of program. In the end of the file, the functions to be exported are listed in exports clause.
Delphi does not require LIB files to import functions from DLLs. To link to a DLL, external keyword is used in function declaration.
In Visual Basic (VB), only run-time linking is supported; but in addition to using LoadLibrary and GetProcAddress API functions, ''declarations'' of imported functions are allowed.
When importing DLL functions through declarations, VB will generate a run-time error if the DLL file cannot be found. The developer can catch the error and handle it appropriately.
Programming examples
Creating DLL exports
Using DLL imports
Using explicit run-time linking
Component Object Model
See also
External links
References

Background


The original purpose for DLLs was saving both disk space and memory required for applications by storing it locally on the hard drive. In a conventional non-shared library, sections of code are simply added to the calling program; if two programs use the same routine, the code has to be included in both. Instead, code which multiple applications share can be separated into a DLL which only exists as a single, separate file, loaded only once into memory during usage. Extensive use of DLLs allowed early versions of Windows to work under tight memory conditions.
DLLs provide the standard benefits of shared libraries, such as modularity. Modularity allows changes to be made to code and data in a single self-contained DLL shared by several applications without any change to the applications themselves. This basic form of modularity allows for relatively compact patches and service packs for large applications, such as Microsoft Office, Microsoft Visual Studio, and even Microsoft Windows itself.
Another benefit of the modularity is the use of generic interfaces for plug-ins. A single interface may be developed which allows old as well as new modules to be integrated seamlessly at run-time into pre-existing applications, without any modification to the application itself. This concept of dynamic extensibility is taken to the extreme with ActiveX.
While DLLs provide many benefits, they have a number of drawbacks, collectively called "DLL hell". Currently, Microsoft .NET is promoted as a solution to the problems of DLL hell.

Features


Memory management

In Win32, the DLL files are organized into ''sections''. Each section has its own set of attributes, such as being writable or read-only, executable (for code) or non-executable (for data), and so on.
The code in a DLL is usually shared among all the processes that use the DLL; that is, they occupy a single place in physical memory, and do not take up space in the page file. If the physical memory occupied by a code section is to be reclaimed, its contents are discarded, and later reloaded directly from the DLL file as necessary.
In contrast to code sections, the data sections of a DLL are usually private; that is, each process using the DLL has its own copy of all the DLL's data. Optionally, data sections can be made shared, allowing inter-process communication via this shared memory area. However, because user restrictions do not apply to the use of shared DLL memory, this creates a security hole; namely, one process can corrupt the shared data, which will likely cause all other sharing processes to behave undesirably. For example, a process running under a guest account can in this way corrupt another process running under a privileged account. This is an important reason to avoid the use of shared sections in DLLs.
If a DLL is compressed by certain executable packers (e.g. UPX), all of its code sections are marked as read-and-write, and will be unshared. Read-and-write code sections, much like private data sections, are private to each process. Thus DLL's with shared data sections should not be compressed if they are intended to be used simultaneously by multiple programs, since each program instance would have to carry its own copy of the DLL, resulting in increased memory consumption.
Import libraries

Linking to dynamic libraries is usually handled by linking to an import library when building or linking to create an executable file. The created executable then contains an import address table (IAT) to which all dll function calls are referenced (each referenced dll function contains its own entry in the IAT). At run-time, the IAT is filled with appropriate addresses that point directly to a function in the separately-loaded dll.
Like static libraries, import libraries for DLLs are noted by the .lib file extension. For example, kernel32.dll, the primary dynamic library for Windows' base functions such as file creation and memory management, is linked to via kernel32.lib...
Symbol resolution and binding

Each function exported by a DLL is identified by a numeric ordinal and optionally a name. Likewise, functions can be imported from a DLL either by ordinal or by name. The ordinal represents the position of the functions address pointer in the DLL Export Address table. It is common for internal functions to be exported by ordinal only. For most Windows API functions only the names are preserved across different Windows releases; the ordinals are subject to change. So, one cannot reliably import Windows API functions by their ordinals.
Importing functions by ordinal provides only slightly better performance than importing them by name: export tables of DLLs are ordered by name, so a binary search can be used to find a function. The index of the found name is then used to lookup the ordinal in the Export Ordinal table. In 16-bit Windows, the name table was not sorted, so the name lookup overhead was much more noticeable.
It is also possible to ''bind'' an executable to a specific version of a DLL, that is, to resolve the addresses of imported functions at compile-time. For bound imports, the linker saves the timestamp and checksum of the DLL to which the import is bound. At run-time Windows checks to see if the same version of library is being used, and if so, Windows bypasses processing the imports. Otherwise, if the library is different from the one which was bound to, Windows processes the imports in a normal way.
Bound executables load somewhat faster if they are run in the same environment that they were compiled for, and exactly the same time if they are run in a different environment, so there's no drawback for binding the imports. For example, all the standard Windows applications are bound to the system DLLs of their respective Windows release. A good opportunity to bind an application's imports to its target environment is during the application's installation.
Explicit run-time linking

DLL files may be explicitly loaded at run-time, a process referred to simply as ''run-time dynamic linking'' by Microsoft, by using the LoadLibrary (or LoadLibraryEx) API function. The GetProcAddress API function is used to lookup exported symbols by name, and FreeLibrary — to unload the DLL. These functions are analogous to dlopen, dlsym, and dlclose in the POSIX standard API.
Note that with implicit run-time linking, referred to as ''load-time dynamic linking'' by Microsoft, if the linked DLL file cannot be found, Windows will display an error message and fail to load the application. The application developer cannot handle the absence of DLL files linked implicitly by the compile-time linker. On the other hand, with explicit run-time linking, developers have the opportunity to provide a graceful fall-back facility.
The procedure for explicit run-time linking is the same in any language, since it depends on the Windows API rather than language constructs.

Compiler and language considerations


=== Delphi

In the heading of a source file, the keyword library is used instead of program. In the end of the file, the functions to be exported are listed in exports clause.
Delphi does not require LIB files to import functions from DLLs. To link to a DLL, external keyword is used in function declaration.
Microsoft Visual Basic

In Visual Basic (VB), only run-time linking is supported; but in addition to using LoadLibrary and GetProcAddress API functions, ''declarations'' of imported functions are allowed.
When importing DLL functions through declarations, VB will generate a run-time error if the DLL file cannot be found. The developer can catch the error and handle it appropriately.
C and C++ ===
Microsoft Visual C++ (MSVC) provides a number of extensions to standard C++ which allow functions to be specified as imported or exported directly in the C++ code; these have been adopted by other Windows C and C++ compilers, including Windows versions of GCC. These extensions use the attribute __declspec before a function declaration. When external names follow the C naming conventions, they must also be declared as extern "C" in C++ code, in order to prevent it from using C++ naming conventions.
Besides specifying imported or exported functions using __declspec attributes, they may be listed in IMPORT or EXPORTS section of the DEF file used by the project. The DEF file is processed by the linker, rather than the compiler, and thus it is not specific to C++.
DLL compilation will produce both DLL and LIB files. The LIB file is used to link against a DLL at compile-time; it is not necessary for run-time linking. Unless your DLL is a COM server, the DLL file must be placed in one of the directories listed in the PATH environment variable, or the default system directory, or in the same directory as the program using it. COM server DLLs are registered using regsvr32.exe, which places the DLL's location and its globally unique ID (GUID) in the registry. Programs can then use the DLL by looking up its GUID in the registry to find its location.

Programming examples


Creating DLL exports

The following examples show language Specific bindings for exporting symbols from DLLs.
'Delphi'
library Example;
// Function that adds two numbers
function AddNumbers(a, b: Double): Double; cdecl;
begin
AddNumbers := a + b
end;
// Export this function
exports
AddNumbers;
// DLL initialization code: no special handling needed
begin
end.
'C and C++'
#include
// Export this function
extern "C" __declspec(dllexport) double AddNumbers(double a, double b);
// DLL initialization function
BOOL APIENTRY
DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}

// Function that adds two numbers
double AddNumbers(double a, double b)
{
return a + b;
}
Using DLL imports

The following examples show how to use language specific bindings to import symbols for linking against a DLL at compile-time.
'Delphi'
program Example;
{$APPTYPE CONSOLE}
// Import function that adds two numbers
function AddNumbers(a, b: Double): Double; cdecl; external 'Example.dll';
var result: Double;
begin
result := AddNumbers(1, 2);
Writeln('The result was: ', result)
end.
'C and C++'
Make sure you include Example.lib file(assuming that Example.dll is generated) in the project (Add Existing Item option for Project!)before static linking. The file Example.lib is automatically generated by the compiler when compiling the DLL. Not executing the above statement would cause linking error as the linker would not know where to find the definition of AddNumbers. You also need to copy the DLL Example.dll to the location where the the .exe file would be generated by the following code.
#include
#include
// Import function that adds two numbers
extern "C" __declspec(dllimport) double AddNumbers(double a, double b);
int main(int argc, char

★ argv)
{
double result = AddNumbers(1, 2);
printf("The result was: %f
", result);
return 0;
}
Using explicit run-time linking

The following examples show how to use the run-time loading and linking facilities using language specific WIN32 API bindings.
'Microsoft Visual Basic'
Option Explicit
Declare Function AddNumbers Lib "Example.dll" _
(ByVal a As Double, ByVal b As Double) As Double
Sub Main()
Dim Result As Double
Result = AddNumbers(1, 2)
Debug.Print "The result was: " & Result
End Sub
'Delphi'
program Example;
{$APPTYPE CONSOLE}
uses
Windows;
Type
AddNumbersProc = function (a, b: Double): Double; cdecl;
var
result: Double;
hInstLib: HMODULE;
AddNumbers: AddNumbersProc;
begin
hInstLib := LoadLibrary('example.dll');
if hInstLib <> 0 then
begin
AddNumbers := GetProcAddress(hInstLib, 'AddNumbers');
if Assigned(AddNumbers) then
begin
result := AddNumbers(1, 2);
Writeln('The result was: ', result);
end
else
begin
Writeln('ERROR: unable to find DLL function');
ExitCode := 1;
end;
FreeLibrary(hInstLib);
end
else
begin
Writeln('ERROR: Unable to load library');
ExitCode := 1;
end;
ExitCode := 0;
end.
'C and C++'
#include
#include
// DLL function signature
typedef double (
★ importFunction)(double, double);
int main(int argc, char

★ argv)
{
importFunction addNumbers;
double result;
// Load DLL file
HINSTANCE hinstLib = LoadLibrary("Example.dll");
if (hinstLib == NULL) {
printf("ERROR: unable to load DLL
");
return 1;
}
// Get function pointer
addNumbers = (importFunction)GetProcAddress(hinstLib, "AddNumbers");
if (addNumbers == NULL) {
printf("ERROR: unable to find DLL function
");
FreeLibrary(hinstLib);
return 1;
}
// Call function.
result = addNumbers(1, 2);
// Unload DLL file
FreeLibrary(hinstLib);
// Display result
printf("The result was: %f
", result);
return 0;
}

Component Object Model


The Component Object Model (COM) extends the DLL concept to object-oriented programming. Objects can be called from another process or hosted on another machine. COM objects have unique GUIDs and can be used to implement powerful back-ends to simple GUI front ends such as Visual Basic and ASP. They can also be programmed from scripting languages. COM objects are more complex to create and use than DLLs.

See also



Dependency walker, a utility which displays exported and imported functions of DLL and EXE files.

Dynamic Library

Library Linking (Computer Science)

Linker

Loader (computing)

Object File

Shared Library

Static Library

External links



__declspec C++ Language Reference on MSDN

dllexport, dllimport on MSDN

Dynamic-Link Libraries on MSDN

Dynamic-Link Library Functions on MSDN

Microsoft Portable Executable and Common Object File Format Specification

Win32 DLL on www.functionx.com. Tutorial for making and using DLLs

Delay Load Dlls Error Recovery on www.codemaestro.com.

Loading a DLL from memory

List of DLL Files used on Windows XP www.dynamiclink.nl

Creating a Windows DLL with Visual Basic

Using DLLs from native Python code

References



★ Hart, Johnson. ''Windows System Programming Third Edition''. Addison-Wesley, 2005. ISBN 0-321-25619-0

★ Rector, Brent et al. ''Win32 Programming''. Addison-Wesley Developers Press, 1997. ISBN 0-201-63492-9.

This article provided by Wikipedia. To edit the contents of this article, click here for original source.

psst.. try this: add to faves