-1

例如在 Pascal 中,如果我有一个要编译为 DLL 的库:

library Blah;

procedure AddToNum;
begin
  Num := Num + 1;
end;


procedure PrintNum;
begin
  WriteLN(Num);
end;

Exports AddToNum;
Exports PrintNum;


var
  Num: Integer;

begin
  Num := 0
end.

理想情况下,用户只需调用 AddToNum 和 PrintNum 例程,它就会这样做。但是,您实际上必须传入参数,这意味着用户必须跟踪我将使用的所有变量。这样做的理想方法是什么?指针什么的?

我正在寻找函数调用之间相同的变量,就像某种“全局”

4

1 回答 1

1

将您的 DLL 代码(运行的实际代码)移动到一个单独的单元(例如,DLLCode.pas),在实现部分的顶部声明变量,并让您的.DPR文件只使用该单元。所有实际代码都进入DLLCode.pas,并且变量的可见性遵循正常的 Pascal 范围规则。

这是一个示例 DLL (DLLSample.dprDLLCode.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关闭它。

于 2012-11-16T21:23:39.810 回答