DLL的编写和使用

来源:互联网 发布:朱仙镇木版年画 淘宝 编辑:程序博客网 时间:2024/06/05 14:46

开使你的第一个DLL专案 1.File->Close all->File->New﹝DLL﹞

 代码:

//自动产生Code如下:

 ibrary Project2;

//这有段废话。

  uses    

SysUtils,   Classes;

{$R *.RES}

begin

end.

2.加个Func进来:

代码:

 library Project2;

uses  

 SysUtils,   Classes;       

Function MyMax ( X , Y : integer ) : integer ; stdcall ;        

 begin    

    if X > Y then    

        Result := X    

    else    

        Result := Y ;  

      end ;  

  //切记:Library 的名字大小写没关系,可是DLL-Func的大小写就有关系了。    

//    在 DLL-Func-Name写成MyMax与myMAX是不同的。如果写错了,立即的结果是你调用到此DLL的AP根本开不起来。    

 //参数的大小写就没关系了。甚至不必同名。如原型中是 (X,Y:integer)但引用时写成(A,B:integer),那是没关系的。    

//切记:要再加个stdcall。书上讲,如果你是用Delphi写DLL,且希望不仅给 Delphi-AP也希望BCB/VC-AP等使用的话,那你最好加个Stdcall ; 

 //参数型态:Delphi有很多种它自己的变量型态,这些当然不是DLL所喜欢的,Windows/DLL的母语应该是C。所以如果要传进传出DLL的参数,我们尽可能照规矩来用。这两者写起来,后者会麻烦不少。如果你对C不熟的话,那也没关系。我们以后再讲。

{$R *.RES} begin end.

3.将这些可共享的Func送出DLL,让外界﹝就是你的Delphi-AP啦﹞使用:

光如此,你的AP还不能用到这些,你还要加个Exports才行。 代码:

{$R *.RES}

exports

    MyMax ;

begin

end.

4.好了,可以按 Ctrl-F9编译了。此时可不要按F9。DLL不是EXE不可单独执行的,如果你按F9,会有ErrorMsg的。这时如果DLL有Error,请修正之。再按Ctrl-F9。此时可能有Warning,不要紧,研究一下,看看就好。再按Ctrl-F9,此时就『Done , Compiled 』。同目录就会有个 *.dll 。恭喜,大功告成了。

library Project2;{ Important note about DLL memory management: ShareMem must be the  first unit in your library's USES clause AND your project's (select  Project-View Source) USES clause if your DLL exports any procedures or  functions that pass strings as parameters or function results. This  applies to all strings passed to and from your DLL--even those that  are nested in records and classes. ShareMem is the interface unit to  the BORLNDMM.DLL shared memory manager, which must be deployed along  with your DLL. To avoid using BORLNDMM.DLL, pass string information  using PChar or ShortString parameters. }uses  SysUtils,  Classes;{$R *.res}Function MyMax ( X , Y : integer ) : integer ; stdcall ;begin  if X > Y then            Result := X    else            Result := Yend;exports    MyMax ;beginend.


 二、进行测试:开个新application:

 1.加个TButton 代码:

 ShowMessage ( IntToStr(MyMax(30,50)) ) ;

2.告知Exe到那里抓个Func 代码:

 //在Form,interface,var后加

Function MyMax ( X , Y : integer ) : integer ; stdcall ;

 external 'MyTestDLL.dll' ;

 // MyTestDLL.dll为你前时写的DLL项目名字,DLL名字大小写没关系。不过记得要加extension的.DLL。在Win95或NT, 是不必加 extension,但这两种OS,可能越来越少了吧。

unit Unit1;interfaceuses  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;Function MyMax ( X , Y : integer ) : integer ; stdcall ;external 'Project2.dll' ;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);begin    ShowMessage ( IntToStr(MyMax(30,50)) ) ;end;end.


 

0 0
原创粉丝点击