在一个典型的窗体界面的EXE程序里,数据模块的实例会被“自动地”建立,如下:
program test1;
uses
Forms,
Unit1 in 'Unit1.pas' {Form1},
Unit2 in '../Unit2.pas' {DataModule2: TDataModule};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
//数据模块的实例在程序启动时被建立
Application.CreateForm(TDataModule2, DataModule2);
Application.Run;
end.
而在一个COM组件的DLL文件里,并没有代码直接创建数据模块的实例,所以如果你要访问
其中的成员,自然就要出错了。因此,应重载COM组件的Initialize方法和Destroy方法,在
Initialize方法中建立数据模块的实例,在Destroy方法中销毁之。
例:
type
TWebServe = class(TASPObject, IWebServe)
private
FDM: TMyDM;
//TMyDM就是我的数据模块类名
protected
public
procedure Initialize;
override;
destructor Destroy;
override;
end;
procedure TWebServe.Initialize;
begin
inherited;
FDM := TaspDM.Create(Forms.Application);
//建立数据模块的实例
end;
destructor TWebServe.Destroy;
begin
inherited;
FDM.Free;
//销毁数据模块实例
end;