Delphi DLL使用接口和调用的方法

来源:互联网 发布:及壮,知向廉洛之学 编辑:程序博客网 时间:2024/05/17 06:52

Delphi对接口采用引用计数的方法管理对象生命周期,但是DLL中输出的对象可能不是被Delphi调用,其引用计数不一定正确,因此DLL中接口对象的生命周期不由Delphi编译器自动生成的代码管理,而是程序员自己控制,所以上面的工厂包括构造和解析两个接口对象的生命周期管理方法。

所有接口对象应该集成自下面的接口,而不应该继承自Delphi自带的TInterfacedObject:

如果在DLL的函数中使用了字符串,还有记得在DLL和调用DLL的工程中单元的首行加入ShareMem,使用ShareMem后在发布执行执行程序是记得包含borlndmm.dll。

(一)DLL源码:

接口定义单元uInf.pas;

unit uInf;


interface


type


  TIntObject = class(TObject, IInterface)
  protected
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;


  ITest = interface
    ['{0FA49A71-48BF-40CD-9D77-63B233C4F717}']
    function GetMethod: Integer;
  end;

implementation


function TIntObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;


function TIntObject._AddRef: Integer;
begin
  Result := -1;
end;


function TIntObject._Release: Integer;
begin
  Result := -1
end;


end.

接口实现单元uDo.pas

unit uDo;


interface


uses Classes, Dialogs, SysUtils, uInf;


type
  TTest = class(TIntObject, ITest)
  public
    function GetMethod: Integer;
  public
    constructor Create;
    destructor Destroy; override;
  end;


function GetITest: ITest;


var
  gTest: TTest;
  
implementation



{ TTest }


constructor TTest.Create;
begin


end;


destructor TTest.Destroy;
begin


  inherited;
end;


function TTest.GetMethod: Integer;
begin
  ShowMessage('TTest.GetMethod');
end;


function GetITest: ITest;
begin
  if not Assigned(gTest) then
    gTest := TTest.Create;
  Result := gTest;
end;


initialization
  GetITest();


finalization
  if Assigned(gTest) then
    FreeAndNil(gTest);


end.


执行程序在调用DLL接口时引用接口单元uInf.pas

Proc = function: IInterface;

加载:

var
  P: Proc;
begin
  P := nil;
  myDLLHandle := loadlibrary('Project2.dll');
  P := GetProcAddress(myDLLHandle, 'GetITest');
  FTestObj := ITest(P);
end;

调用:

FTestObj.GetMethod();

释放:

  Pointer(FTestObj) := nil;
  FreeLibrary(myDLLHandle);

0 0
原创粉丝点击