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.
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.
|
DLL_PROCESS_DETACH |
Indicates 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 or (dlclose 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). |
On Linux, these are defined in the
Libc unit.
In the body of the procedure, you can specify actions to take depending on which parameter is passed to the procedure.
Writing dynamically loadable libraries
在System单元中声明的变量中,有几个对库编程有特殊影响。用IsLibrary可以检测代码是执行在应用程序中还是执行在库中;在应用程序中IsLibrary总是为False,在库中总是为True。在库的整个生命周期中,HInstance包含了库的实例句柄。在库中,系统变量CmdLine总是为nil。
DLLProc变量允许库监视操作系统对库的入口点的调用。这一特性通常只用于那些支持多线程的库。DLLProc变量在Windows和Linux中都是可用的,但其用法不同。在Windows中,DLLProc用于多线程应用程序;在Linux中,它用于确定库在何时被卸载。对于所有的退出操作,应使用结束节(finalization sections)而不使用退出过程。
要监视操作系统调用,需要创建一个回调函数,该函数接受一个整数参数,例如,
procedure
DLLHandler(Reason: Integer);
并把该过程的地址赋给DLLProc变量。当过程被调用时,将传递下列值之一到回调函数:
|
DLL_PROCESS_DETACH |
该值表示库作为完全退出的结果或调用FreeLibrary(在Linux中是dlclose)的结果,从调用库的进程中被分离。 |
|
DLL_THREAD_ATTACH |
该值表示当前进程创建了一个新的线程(仅适用于Windows)。 |
|
DLL_THREAD_DETACH |
该值表示线程完全退出(仅适用于Windows)。 |
对于Linux,这些定义在Libc单元中。
在过程(上面例子中的回调函数)的主体中,可以根据传递到过程的是哪一个参数来指定相应的动作。