유돌이

calendar

1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

Notice

2011. 7. 5. 13:10 델파이

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 select File | New ... DLL. This will create a new DLL template in the editor window. Select the default text and replace it with the next piece of code.

 library TestLibrary;
 
 uses SysUtils, Classes, Dialogs;
 
 procedure DllMessage; export;
 begin
   ShowMessage('Hello world from a Delphi DLL') ;
 end;
 
 exports DllMessage;
 
 begin
 end. 
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 begin with the reserved word Library. This is then followed by a uses clause for any needed units. In this simple example, there then follows a procedure called DllMessage which does nothing except showing a simple message.

At the end of the source code we find an exports statement. This 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 we can have, let's say, 5 procedures in a DLL and only 2 of them (listed in the exports section) can be called from an external program (the remaining 3 are "sub procedures" in a DLL).

In order to use this simple DLL, we have to compile it by pressing Ctrl+F9. This should create a DLL called SimpleMessageDLL.DLL in your projects folder.

Finally, let's see how to call the DllMessage procedure from a (statically loaded) DLL.

To import a procedure contained in a DLL, we use the keyword external in the procedure declaration. For example, given the DllMessage procedure shown earlier, the declaration in the calling application would look like :

 procedure DllMessage; external 'SimpleMessageDLL.dll' 
the actual call to a procedure will be nothing more than
 DllMessage; 
The entire code for a Delphi form (name: Form1) with a TButton on it (name: Button1) that's calls the DLLMessage function could be:
 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.dll'
 
 implementation
 
 {$R *.dfm}
 
 procedure TForm1.Button1Click(Sender: TObject) ;
 begin
    DllMessage;
 end;
 
 end. 

posted by 유돌이