Quick start manual
9-8
Delphi Language Guide
Writing dynamically loadable libraries
Global variables in a library
Global variables declared in a shared library cannot be imported by a Delphi
application.
A library can be used by several applications at once, but each application has a copy
of the library in its own process space with its own set of global variables. For
multiple libraries—or multiple instances of a library—to share memory, they must
use memory-mapped files. Refer to the your system documentation for further
information.
Libraries and system variables
Several variables declared in the System unit are of special interest to those
programming libraries. Use IsLibrary to determine whether code is executing in an
application or in a library; IsLibrary is always False in an application and True in a
library. During a library’s lifetime, HInstance contains its instance handle. CmdLine is
always nil in a library.
The DLLProc variable allows a library to monitor calls that the operating system
makes to the library entry point. This feature is normally used only by libraries that
support multithreading. DLLProc is available on both Windows and Linux but its use
differs on each. On Windows, DLLProc is used in multithreading applications; on
Linux, it is used to determine when your library is being unloaded. You should use
finalization sections, rather than exit procedures, for all exit behavior. (See “The
finalization section” on page 3-5.)
To monitor operating-system calls, create a callback procedure that takes a single
integer parameter—for example,
procedure DLLHandler(Reason: Integer);
and assign the address of the procedure to the DLLProc variable. When the procedure
is called, it passes to it one of the following values.
In the body of the procedure, you can specify actions to take depending on which
parameter is passed to the procedure.
DLL_PROCESS_DETACHIndicates that the library is detaching from the address
space of the calling process as a result of a clean exit or a
call to FreeLibrary (dlclose on Linux).
DLL_PROCESS_ATTACHIndicates that the library is attaching to the address space
of the calling process as the result of a call to LoadLibrary
(dlopen on Linux).
DLL_THREAD_ATTACH Indicates that the current process is creating a new thread
(Windows only).
DLL_THREAD_DETACH Indicates that a thread is exiting cleanly (Windows only).