将您的 DLL 代码(运行的实际代码)移动到一个单独的单元(例如,DLLCode.pas
),在实现部分的顶部声明变量,并让您的.DPR
文件只使用该单元。所有实际代码都进入DLLCode.pas
,并且变量的可见性遵循正常的 Pascal 范围规则。
这是一个示例 DLL (DLLSample.dpr
和DLLCode.pas
),以及一个使用它的测试控制台应用程序。所有代码都在 Delphi 2007 和 Windows 7 64 位下编译并正确执行。
DllSample.dpr:
library DLLSample;
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
uses
SysUtils,
Classes,
DLLCode in 'DLLCode.pas';
{$R *.res}
begin
end.
DllCode.pas:
unit DLLCode;
interface
procedure AddToNum; stdcall;
procedure PrintNum; stdcall;
exports
AddToNum,
PrintNum;
implementation
// Num is only visible from here down, and starts with a value of zero when the
// DLL is first loaded. It keeps it's value until the DLL is unloaded, which is
// typically when your app is exited when using static linking, or when you
// FreeLibrary() when dynamically linking.
var
Num: Integer = 0;
procedure AddToNum;
begin
Inc(Num); // Same as Num := Num + 1;
end;
procedure PrintNum;
begin
WriteLn(Num);
end;
end.
DllTestApp.dpr:
program DLLTestApp;
{$APPTYPE CONSOLE}
uses
SysUtils;
// Links to the procedures in the DLL. Note that the DLL has to be
// in the same folder, or located somewhere on the Windows PATH. If
// it can't be found, your app won't run.
procedure AddToNum; external 'DLLSample.dll';
procedure PrintNum; external 'DllSample.dll';
begin
PrintNum; // Print initial value
AddToNum; // Add to it twice
AddToNum;
PrintNum; // Print new value
ReadLn; // Wait for Enter key
end.
这输出:
0
2
在控制台窗口中,等待您点击Enter关闭它。