插件框架

插件框架

plugin.json

{
	"plugin":
	[
		{
			"plugid":1000,
			"plugname":"bpl1.bpl",
			"remark":"REST CRUD"
		},
		{
			"plugid":1001,
			"plugname":"bpl2.bpl",
			"remark":"REST文件传输"
		},
		{
			"plugid":2000,
			"plugname":"bpl3.bpl",
			"remark":"binary CRUD"
		},
		{
			"plugid":2001,
			"plugname":"bpl4.bpl",
			"remark":"binary文件传输"
		},
		{
			"plugid":3000,
			"plugname":"bpl5.bpl",
			"remark":"binary雪花ID"
		}
	]
}

  plugin.manager.pas

/// <author>cxg 2024-1-25</author>
/// 包扩展名,windows是.bpl;LINUX是.so

unit plugin.manager;

interface

uses
  System.Rtti, global, System.Classes, yn.log, System.SysUtils,
  system.JSON, json.help;

type
  TPlug = record  //插件信息记录
    plugid, plughandle: Integer;
    plugname, remark: string;
  end;

type
  TPlugs = array of TPlug;  //插件信息记录数组

procedure LoadPlugs;  /// 加载所有的插件
function GetPlug(plugid: Integer): TPlug;   /// 获取一个插件信息记录

var
  PlugArray: TPlugs;
  PlugNames: TStringList;   //已加载的包

implementation

function GetPlug(plugid: Integer): TPlug;
begin
  var p: TPlug;
  for p in PlugArray do
    if p.plugid = plugid then
    begin
      Result := p;
      Exit;
    end;
end;

function ExistsPlug(Plugname: string): Boolean;
begin
  Result := PlugNames.IndexOf(Plugname) <> -1
end;

procedure LoadPlugs;
begin
  var jo: TJSONObject:= TJSONObject.Create;
  jo.LoadFromFile(PlugCfg);
  try
    try
      var plugname: string;
      var ja: TJSONArray := jo.A['plugin'];
      SetLength(PlugArray, ja.Count);   // 设置插件数组 下标
      for var i: integer := 0 to ja.Count - 1 do
      begin
        var o: TJSONObject := ja.Items[i] as TJSONObject;
        plugname := o.S['plugname'];
        PlugArray[i].plugid := o.I['plugid'];
        PlugArray[i].plugname := plugname;
        PlugArray[i].remark := o.S['remark'];
        if not ExistsPlug(plugname) then     //不重复加载.bpl or .so
        begin
          var h: Cardinal := LoadPackage(PlugPath + PlugArray[i].plugname);  //加载插件
          PlugArray[i].plughandle := h;
          var s: string;
          if h = 0 then
          begin
            s := 'Load ' + PlugArray[i].plugname + ' fail.';
            Writeln(s);
          end
          else
          begin
            PlugNames.Add(plugname);
            s := 'Load ' + PlugArray[i].plugname + '(' + PlugArray[i].remark +')';
            Writeln(s);
          end;
          WriteLog(s);
        end;
      end;
    except
      on E: Exception do
        WriteLog('plugin.manager.LoadPlugs()' + E.Message);
    end;
  finally
    jo.Free;
  end;
end;

initialization
  PlugNames := TStringList.Create;

finalization
  FreeAndNil(PlugNames);

end.

  

posted @ 2024-01-25 10:51  delphi中间件  阅读(61)  评论(0编辑  收藏  举报