您的位置:首页 > 其它

动态和静态调用DLL

2012-02-09 20:46 197 查看
写一个简单的动态库,动态库中有一个求和函数,函数返回求和结果

DLL的工程单元代码:

library wudll;

uses
SysUtils,
Classes,
Unit1 in 'Unit1.pas';

{$R *.RES}
exports   //用exports 声明函数出口
Wuadd;

begin
end.

DLL中的写了函数体的单元Unit1代码:

unit Unit1;

interface
function Wuadd(anum1,Anum2:Integer):Integer;stdcall; //函数声明
//Delphi 默认采用 register 调用约定,如果dll涉及跨语言调用,最好明确指出采用 stdcall 调用约定
implementation

function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;  //函数体
begin
Result:=0;
Result:=Anum1+Anum2;
end;
end.

---------------------------------------

以下为调用该动态库

新建Form1, 点击按钮则调用DLL计算Edit1和Edit2的和,并将结果赋值给Edit3

unit Unit1;

interface

uses
ShareMem,Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
//ShareMem 如果dll涉及长字符串的参数或变量,需要在 uses 第一的位置引用 ShareMem 单元。
type
Twuabc=function (num1,num2:Integer):Integer;stdcall; //动态调用声明 必须写在type下
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Edit3: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;external'd:\wudll.dll';
//静态调用DLL声明,必须写在type外面或implementation下面,这里的函数名必须和DLL中的函数名相同,大小写敏感
var
Form1: TForm1;
implementation
{$R *.DFM}

//function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;external'd:\wudll.dll';

procedure TForm1.Button1Click(Sender: TObject);//动态调用DLL
var
wuhandle:THandle;
wufunc:Twuabc;
str1:Integer;
begin wuhandle:=LoadLibrary('d:/wudll.dll'); //加载 DLL 到内存
if wuhandle<>0 then begin
try
@wufunc:=GetProcAddress(wuhandle,'Wuadd'); //获得函数的入口地址
if @wufunc<>nil then begin
str1:=wufunc(StrToInt(Edit1.Text),StrToInt(Edit2.Text)); //调用DLL中的函数
Edit3.Text:=IntToStr(str1);
end;
finally
FreeLibrary(wuhandle);
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);//静态调用DLL
var
str1:Integer;
begin
str1:=Wuadd(StrToInt(Edit1.Text),StrToInt(Edit2.Text)); //调用DLL中的函数
Edit3.Text:=IntToStr(str1);
end;

end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: