、Dll文件的编写 调用 说明

1>新建Dll文件TestLib.dll

新建Unit文件U_TestFunc

U_TestFunc代码如下:

unit U_TestFunc;

interface

uses //尽可能的少uses这样会缩小dll的体积

  SysUtils;

//求和

function Sum(x1,x2: Integer): Integer; stdcall

implementation

function Sum(x1,x2: Integer): Integer; stdcall

begin

  Result := x1+x2;

end;

end.

TestLib代码如下:

library TestLib;

uses    SysUtils,

U_TestFunc in 'U_TestFunc.pas';

{$R *.res}

exports

Sum;

begin

end.

2>调用方法  源码如下:

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,    Dialogs, StdCtrls, Buttons;

type

  TForm1 = class(TForm)

  Edit1: TEdit;

BitBtn1: TBitBtn;

Edit2: TEdit;

BitBtn2: TBitBtn;

   procedure BitBtn1Click(Sender: TObject);

   procedure BitBtn2Click(Sender: TObject);

private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

implementation

{$R *.dfm}

  function Sum(a1,a2: Integer): Integer; stdcall; external 'C:\TestLib.dll';

procedure TForm1.BitBtn1Click(Sender: TObject);

begin

  //if FileExists('C:\TestLib.dll') then  这里感觉这两个函数没有什么区别,文件在本地不在本地貌似效果都一样。

   if LocaleFileExists('C:\TestLib.dll') then

        Edit1.Text := IntToStr(Sum(100,200))

  else

        ShowMessage('文件不存在!');

end;

procedure TForm1.BitBtn2Click(Sender: TObject);

type

TIntFunc = function(a1,a2: Integer): Integer; stdcall;

var

Th: THandle;

Tf: TIntFunc;

begin

Th := LoadLibrary('C:\TestLib.dll');

 if Th>0 then

  begin

try

@Tf := GetProcAddress(Th, PAnsiChar('Sum'));

if @Tf<>nil then

begin

Edit2.Text := IntToStr(Tf(100,200));

end else

ShowMessage('Sum函数没有找到!');

finally

FreeLibrary(Th); //释放Dll

end;

end else

ShowMessage('TestLib.dll文件没有找到!');

end;

end.

上一篇:Android Small插件化框架源码分析


下一篇:【MyBatis源码分析】插件实现原理