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 exit procedure using
the ExitProc variable, as described in Exit procedures; the exit
procedure executes when the library is 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 exit procedure.
library
Test;
var
SaveExit: Pointer;
procedure
LibExit;
begin
... // library exit code
ExitProc := SaveExit; // restore exit procedure chain
end;
begin
... // library initialization code
SaveExit := ExitProc; // save exit procedure chain
ExitProc := @LibExit; // install LibExit exit procedure
end.
When a library is unloaded, it’s exit procedures are executed by repeated calls to the address stored in ExitProc, until ExitProc becomes nil. 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 exit procedure.
Writing dynamically loadable libraries
在库的块中的语句组成了库的初始化(initialization)代码。库每次被加载时这些语句都被执行一次。初始化代码典型的任务是注册窗口类和初始化变量。库的初始化代码还可以通过ExitProc变量装入退出过程,就象Exit过程的作用;当库被卸载时,退出过程被执行。
库的初始化代码可以通过设置ExitCode变量为非零值来标记一个错误。ExitCode变量在System单元中声明,缺省值为零,表示成功的初始化。如果库的初始化代码设置ExitCode为其他值,那么库将被卸载并且调用库的应用程序收到失败的通知。同样,如果一个未处理的异常在初始化代码执行中出现,那么调用该库的应用程序也将收到加载库失败的通知。
下面是库的初始化代码及退出过程的例子。
library
Test;
var
SaveExit: Pointer;
procedure
LibExit;
begin
... //库的退出代码
ExitProc := SaveExit; //恢复退出过程链
end;
begin
... //库的初始化代码
SaveExit := ExitProc; //保存退出过程链
ExitProc := @LibExit; //装入退出过程LibExit
end.
库被卸载时,其退出过程被存储在ExitProc变量中的地址重复调用,直到ExitProc变成nil。被库使用的所有单元,其初始化部分在库的初始化代码执行之前被执行,并且这些单元的结束(finalization)部分在库的退出过程执行之后被执行。