Friday, May 15, 2020
How to Create and Use DLLs in Delphi
A Dynamic Link Library (DLL) is a collection of routines (small programs) that that can be called by applications and other DLLs. Like units, they contain code or resources that can be shared between multiple applications. The concept of DLLs is the core of the Windows architectural design, and for the most part, Windows is simply a collection of DLLs. With Delphi, you can write and use your own DLLs and even call functions regardless of whether or not they were developed with other systems or developers, like Visual Basic, or C/C. Creating a Dynamic Link Library The following few lines will demonstrate how to create a simple DLL using Delphi. For the beginning start Delphi and navigate to File New DLL to build a new DLL template. Select the default text and replace it with this: library TestLibrary;uses SysUtils, Classes, Dialogs;procedure DllMessage; export;begin ShowMessage(Hello world from a Delphi DLL) ; end;exports DllMessage;beginend. If you look at the project file of any Delphi application, youââ¬â¢ll see that it starts with the reserved word program. By contrast, DLLs always start with library and then a uses clause for any units. In this example, the DllMessage procedure follows, which doesnt do anything but show a simple message. At the end of the source code is an exports statement which lists the routines that are actually exported from the DLL in a way that they can be called by another application. What this means is that you can have, say, five procedures in a DLL and only two of them (listed in the exports section) can be called from an external program (the remaining three are sub procedures). In order to use this DLL, we have to compile it by pressing CtrlF9. This should create a DLL called SimpleMessageDLL.DLL in your projects folder. Finally, lets take a look at how to call the DllMessage procedure from a statically loaded DLL. To import a procedure contained in a DLL, you can use the keyword external in the procedure declaration. For example, given the DllMessage procedure shown above, the declaration in the calling application would look like this: procedure DllMessage; external SimpleMessageDLL.dll The actual call to a procedure is nothing more than: DllMessage; The entire code for a Delphi form (name: Form1), with a TButton (named Button1) that calls the DLLMessage function, looks something like this: unit Unit1;interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject) ;private{ Private declarations }public{ Public declarations }end;var Form1: TForm1; procedure DllMessage; external SimpleMessageDLL.dllimplementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject) ;begin DllMessage; end;end.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.