DLLコード(実行される実際のコード)を別のユニット(たとえばDLLCode.pas
)に移動し、実装セクションの上部で変数を宣言し、.DPR
ファイルでそのユニットのみを使用するようにします。実際のコードはすべて入りDLLCode.pas
、変数の可視性は通常のPascalスコープルールに従います。
これは、サンプルDLL(DLLSample.dpr
およびDLLCode.pas
)と、それを使用するテストコンソールアプリケーションです。すべてのコードは、Delphi2007およびWindows764ビットでコンパイルおよび適切に実行されます。
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コンソールウィンドウで、を押して閉じるのを待ちます。