Quick start manual

Libraries and packages
9-7
Writing dynamically loadable libraries
Library initialization code
The statements in a library’s block constitute the library’s initialization code. These
statements are executed once every time the library is loaded. They typically perform
tasks like registering window classes and initializing variables. Library initialization
code can also install an entry point procedure using the DllProc variable. The DllProc
variable is similar to an exit procedure, which is described in “Exit procedures” on
page 12-5; the entry point procedure executes when the library is loaded or
unloaded.
Library initialization code can signal an error by setting the ExitCode variable to a
nonzero value. ExitCode is declared in the System unit and defaults to zero, indicating
successful initialization. If a library’s initialization code sets ExitCode to another
value, the library is unloaded and the calling application is notified of the failure.
Similarly, if an unhandled exception occurs during execution of the initialization
code, the calling application is notified of a failure to load the library.
Here is an example of a library with initialization code and an entry point procedure.
library Test;
var
SaveDllProc: Pointer;
procedure LibExit(Reason: Integer);
begin
if Reason = DLL_PROCESS_DETACH then
begin
ƒ // library exit code
end;
SaveDllProc(Reason); // call saved entry point procedure
end;
begin
ƒ // library initialization code
SaveDllProc := DllProc; // save exit procedure chain
DllProc := @LibExit; // install LibExit exit procedure
end.
DllProc is called when the library is first loaded into memory, when a thread starts or
stops, or when the library is unloaded. The initialization parts of all units used by a
library are executed before the library’s initialization code, and the finalization parts
of those units are executed after the library’s entry point procedure.