Delphi uses DLL to implement a simple example of plug-in
This is the code of the DLL
Implementation code:
library MyDll; uses SysUtils, Dialogs, Classes; procedure ShowInfo(info:PChar);stdcall; begin ShowMessage('You selected ['+info+']'); end; function GetCaption:Pchar; begin Result := 'China' ; end; exports ShowInfo, GetCaption; {$R *.res} begin end.
This is the code that calls the form
This example only uses one DLL, so when there are multiple DLLs, you need to loop through the directory where the DLL is located and load the DLLs in sequence.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, ExtCtrls; type TShowInfo = procedure (info:PChar);stdcall; TGetCaption = function : PChar;stdcall; TForm1 = class(TForm) Button1: TButton; Button2: TButton; MainMenu1: TMainMenu; Image1: TImage; procedure Button2Click(Sender: TObject); private { Private declarations } FHandel : THandle; //DLL handle FProAddress: Pointer; //The address of ShowInfo in the DLL showinfo: TShowInfo; //Set for dynamic loading of DLL procedure LoadPlusIn; //Load plug-in (DLL) procedure ItemClick(Sender: TObject); //Custom menu click event public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button2Click(Sender: TObject); begin LoadPlusIn; end; procedure TForm1.ItemClick(Sender: TObject); begin @showinfo := FProAddress ; //Get address if @showinfo <> nil then showinfo(PWideChar(TMenuItem(Sender).Caption)); //Execute ShowInfo in DLL end; procedure TForm1.LoadPlusIn; var getcaption: TGetCaption; item : TMenuItem; begin FHandel := LoadLibrary('MyDll.dll'); / /Loading if FHandel = 0 then begin ShowMessage('Loading failed! '); Exit; end else begin @getcaption := GetProcAddress(FHandel,'GetCaption'); //Get the GetCaption address in the DLL if @getcaption <> nil then begin item := TMenuItem.Create(MainMenu1); //Create a Menu item.Caption := getcaption; //Get the Caption, that is, call GetCaption in the DLL FProAddress := GetProcAddress(FHandel,'ShowInfo'); //Get the address of ShowInfo in the DLL item.OnClick := ItemClick; //Assign the click event to the menu item MainMenu1.Items.Add(item); //Add to the main menuend; end ; end; end.
If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help everyone. Thank you for your support of this site!