首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 從 DLL 導出類別:元類別別名與動態載入實現插件架構

     編輯:Delphi

動機:突破 BPL 包的限制

BPL (Runtime Package) 要求使用者預知具體類別名稱。若需「不知具體類別、僅知基底抽象介面」即可動態載入使用 (插件模式),BPL 無法滿足。解決方案:DLL 導出元類別 (Class Reference)。

核心概念:元類別


type
  TMyBaseForm = class(TForm)
  protected
    function GetTitle: PChar; virtual; abstract;
  end;

  TMyBaseFormClass = class of TMyBaseForm; // 元類別類型
  • TMyBaseFormClass 變數可持有 TMyBaseForm 及其任意子類別的類別本身 (而非實例)
  • 賦值:AClass := TMyBaseForm、AClass := TForm1、AClass := TButton (若繼承關係符合)
  • 動態創建:Form := AClass.Create(Application);

三步驟實現架構

1. 共用介面單元 (主程式 + DLL 共用)


unit BaseIntf;
interface
type
  TMyBaseForm = class(TForm)
  protected
    function GetTitle: PChar; virtual; abstract;
  end;
  TMyBaseFormClass = class of TMyBaseForm;
implementation end.

2. DLL 實作與導出


library PluginDLL;
uses BaseIntf, FormImpl1, FormImpl2, FormImpl3;

function GetClassCount: Integer; stdcall;
begin Result := 3; end; // 導出類別數量

function GetClassTypeByIndex(Index: Integer; var Cls: TMyBaseFormClass): WordBool; stdcall;
begin
  Result := True;
  case Index of
    0: Cls := TFormImpl1;
    1: Cls := TFormImpl2;
    2: Cls := TFormImpl3;
  else Result := False;
  end;
end;

exports GetClassCount, GetClassTypeByIndex;
begin end.
  • 子類別實作 GetTitle 回傳不同字串
  • 專案選項 → Packages → 勾選 Build with Runtime Packages (關鍵!確保類別型別身份一致)

3. 主程式動態載入驅動引擎


var
  DllHandle: THandle;
  GetCount: function: Integer; stdcall;
  GetClass: function(Index: Integer; var Cls: TMyBaseFormClass): WordBool; stdcall;
  I, Count: Integer;
  Cls: TMyBaseFormClass;
  Frm: TMyBaseForm;
  Ok: Boolean;
begin
  DllHandle := LoadLibrary('PluginDLL.dll');
  @GetCount := GetProcAddress(DllHandle, 'GetClassCount');
  @GetClass := GetProcAddress(DllHandle, 'GetClassTypeByIndex');

  Count := GetCount;
  for I := 0 to Count - 1 do begin
    if GetClass(I, Cls) then begin
      Frm := Cls.Create(Application); // 多態創建
      Frm.Caption := Frm.GetTitle;    // 多態呼叫
      Frm.Show;
    end;
  end;
end;

關鍵技術點總結

技術點作用
class of TBase定義元類別型別,讓類別成為可傳遞的值
DLL 導出函數傳回元類別運行期動態發現並取得具體類別型別
Build with Runtime Packages確保主程式與 DLL 共享相同 VCL 型別資訊,is/as 正常運作
多態創建/呼叫主程式完全不知具體類別名,僅透過基底介面操作

應用場景

  • 插件系統:主程式定義抽象介面,第三方開發 DLL 擴充功能
  • 熱插拔模組:運行期載入/卸載功能模組
  • 跨版本相容:DLL 可獨立升級,介面不變即不影響主程式

總結

利用 元類別 + DLL 導出函數 + Runtime Packages,Delphi 可實現真正的「介面導向、運行期發現、動態多態」插件架構。這比 BPL 更靈活,不要求使用者預知具體類別名稱,是構建可擴充應用程式的強大技術。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved