Friday, 7 December 2012



Dynamic-link library (also written unhyphenated), 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 and 64-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. 

Background for DLL

The first versions of Microsoft Windows ran every program in a single address space. Every program was meant to co-operate by yielding the CPU to other programs so that the graphical user interface (GUI) could multitask and be maximally responsive. All operating system level operations were provided by the underlying operating system: MS-DOS. All higher level services were provided by Windows Libraries "Dynamic Link Library." The Drawing API, GDI, was implemented in a DLL called GDI.EXE, the user interface in USER.EXE. These extra layers on top of DOS had to be shared across all running Windows programs, not just to enable Windows to work in a machine with less than a megabyte of RAM, but to enable the programs to co-operate among each other. The Graphics Device Interface code in GDI needed to translate drawing commands to operations on specific devices. On the display, it had to manipulate pixels in the frame buffer. When drawing to a printer, the API calls had to be transformed into requests to a printer. Although it could have been possible to provide hard-coded support for a limited set of devices (like the Color Graphics Adapter display, the HP LaserJet Printer Command Language), Microsoft chose a different approach. GDI would work by loading different pieces of code, called 'device drivers', to work with different output devices.
The same architectural concept that allowed GDI to load different device drivers is that which allowed the Windows shell to load different Windows programs, and for these programs to invoke API calls from the shared USER and GDI libraries. That concept was "dynamic linking."
In a conventional non-shared, "static" library, sections of code are simply added to the calling program when its executable is built at the "linking" phase; if two programs call the same routine, the routine is included in both the programs during the linking stage of the two. With dynamic linking, shared code is placed into a single, separate file. The programs that call this file are connected to it at run time, with the operating system (or, in the case of early versions of Windows, the OS-extension), performing the binding.
For those early versions of Windows (1.0 to 3.11), the DLLs were the foundation for the entire GUI.
  • Display drivers were merely DLLs with a .DRV extension that provided custom implementations of the same drawing API through a unified device driver interface (DDI).
  • The Drawing (GDI) and GUI (USER) APIs were merely the function calls exported by the GDI and USER, system DLLs with .EXE extension.
This notion of building up the operating system from a collection of dynamically loaded libraries is a core concept of Windows that persists even today. 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.
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 the Component Object Model, the underpinnings of ActiveX.
In Windows 1.x, 2.x and 3.x, all Windows applications shared the same address space as well as the same memory. A DLL was only loaded once into this address space; from then on, all programs using the library accessed it. The library's data was shared across all the programs. This could be used as an indirect form of inter-process communication, or it could accidentally corrupt the different programs. With the introduction of 32-bit libraries in Windows 95 every process runs in its own address space. While the DLL code may be shared, the data is private except where shared data is explicitly requested by the library. That said, large swathes of Windows 95, Windows 98 and Windows Me were built from 16-bit libraries, a feature that limited the performance of the Pentium Pro microprocessor when launched, and ultimately limited the stability and scalability of the DOS-based versions of Windows.
Although DLLs are the core of the Windows architecture, they have several drawbacks, collectively called "DLL hell". Microsoft currently promotes .NET Framework as one solution to the problems of DLL hell, although they now promote virtualization-based solutions such as Microsoft Virtual PC and Microsoft Application Virtualization, because they offer superior isolation between applications. An alternative mitigating solution to DLL hell has been implementing side-by-side assembly.

Features of DLL

Since DLLs are essentially the same as EXEs, the choice of which to produce as part of the linking process is for clarity, since it is possible to export functions and data from either.
It is not possible to directly execute a DLL, since it requires an EXE for the operating system to load it through an entry point, hence the existence of utilities like RUNDLL.EXE or RUNDLL32.EXE which provide the entry point and minimal framework for DLLs that contain enough functionality to execute without much support.
DLLs provide a mechanism for shared code and data, allowing a developer of shared code/data to upgrade functionality without requiring applications to be re-linked or re-compiled. From the application development point of view Windows and OS/2 can be thought of as a collection of DLLs that are upgraded, allowing applications for one version of the OS to work in a later one, provided that the OS vendor has ensured that the interfaces and functionality are compatible.
DLLs execute in the memory space of the calling process and with the same access permissions which means there is little overhead in their use but also that there is no protection for the calling EXE if the DLL has any sort of bug.

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) by 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 via kernel32.lib.

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 look up exported symbols by name, and FreeLibrary — to unload the DLL. These functions are analogous to dlopen, dlsym, and dlclose in the POSIX standard API.
// LSPaper draw using OLE2 function if available on client
 
HINSTANCE hOle2Dll ;
 
hOle2Dll = LoadLibraries ( "OLE2.DLL" ) ;
 
if ( hOle2Dll != NULL )
{
  FARPROC lpOleDraw ;
 
  lpOleDraw = GetProcAddress ( hOle2Dll , "OleDraw" ) ;
 
  if ( lpOleDraw != (FARPROC)NULL )
  {
    (*lpOleDraw) (pUnknown , dwAspect , hdcDraw , lprcBounds ) ;
  }
  FreeLibrary ( hOle2Dll ) ;
}
The procedure for explicit run-time linking is the same in any language that supports pointers to functions, since it depends on the Windows API rather than language constructs.

C and C++

Microsoft Visual C++ (MSVC) provides several 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. Note that when C functions are accessed from C++, they must also be declared as extern "C" in C++ code, to inform the compiler that the C linkage should be used.
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 Component Object Model (COM) server, the DLL file must be placed in one of the directories listed in the PATH environment variable, in 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
  Result := a + b;
end;
 
// export this function
exports AddNumbers;
 
// DLL initialization code: no special handling needed
begin
end.
C and C++ (Microsoft visual dialect)
#include <windows.h>
 
// DLL entry function (called on load, unload, ...)
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}
 
// Exported function - adds two numbers
extern "C" __declspec(dllexport) 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
{$APPTYPE CONSOLE}
 
program Example;
 
// import function that adds two numbers
function AddNumbers(a, b : Double): Double; cdecl; external 'Example.dll';
 
// main program
var
   R: Double;
 
begin
  R := AddNumbers(1, 2);
  Writeln('The result was: ', R);
end.
Microsoft Visual 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 .exe file would be generated by the following code.
#include <windows.h>
#include <stdio.h>
 
// 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\n", 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 Windows 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;
 
var
        AddNumbers      : function (a, b: Double): Double; cdecl;
        LibHandle       : HMODULE;
 
begin
        LibHandle := LoadLibrary('example.dll');
 
        if LibHandle = 0 then
        Exit;
 
        AddNumbers := GetProcAddress(LibHandle, 'AddNumbers');
 
        if Assigned( AddNumbers ) then
        Writeln( '1 + 2 = ', AddNumbers( 1, 2 ) );
        else
        Writeln('Error: unable to find DLL function');
 
        FreeLibrary(LibHandle);
end.

C and C++ (Microsoft Visual Dialect)

#include <windows.h>
#include <stdio.h>
 
// DLL function signature
typedef double (*importFunction)(double, double);
 
int main(int argc, char **argv)
{
        importFunction addNumbers;
        double result;
 
        // Load DLL file
        HINSTANCE hinstLib = LoadLibrary(TEXT("Example.dll"));
        if (hinstLib == NULL) {
                printf("ERROR: unable to load DLL\n");
                return 1;
        }
 
        // Get function pointer
        addNumbers = (importFunction)GetProcAddress(hinstLib, "AddNumbers");
        if (addNumbers == NULL) {
                printf("ERROR: unable to find DLL function\n");
                FreeLibrary(hinstLib);
                return 1;
        }
 
        // Call function.
        result = addNumbers(1, 2);
 
        // Unload DLL file
        FreeLibrary(hinstLib);
 
        // Display result
        printf("The result was: %f\n", result);
 
        return 0;
}

Python

import ctypes
 
my_dll = ctypes.cdll.LoadLibrary("Example.dll")
 
# The following "restype" method specification is needed to make
# Python understand what type is returned by the function.
my_dll.AddNumbers.restype = ctypes.c_double
 
p = my_dll.AddNumbers(ctypes.c_double(1.0), ctypes.c_double(2.0))
 
print "The result was:", p





0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!