Delphi DLL使用接口和调用的方法
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);
總結
以上是生活随笔為你收集整理的Delphi DLL使用接口和调用的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《数据结构》---三元组的实现
- 下一篇: Excel Power Query M