读书人

动态调用dll的例子解决办法

发布时间: 2012-03-12 12:45:33 作者: rapoo

动态调用dll的例子
刚学delphi,看了个动态调用dll的例子,有些不明白,把代码贴出来,请高手讲解,谢谢!

这个dll很简单就是求3n,但是有几点不明白,感觉静态调用比动态调用简单多了啊

1.if Handle>32 then。。 不知道为什么要和32做比较呢?
2.if @addc<>nil then。。 这个也迷糊
3.还有就是这个动态调用dll的思想,弄了一个函数指针,然后后面都看不懂了,麻烦讲一下,非常感谢!


一、Dll建立

(一)DLL的建立

library mydll;


uses

base in 'base.pas';


exports

Triple name 'Tr';


{$R *.res}


begin

end.


(二)函数

unit base;


interface


uses windows;


function Triple(N:integer):integer;stdcall;


implementation


function Triple(N:integer):integer;stdcall;

begin

result:=n*3;

end;


end.

二、动态调用

unit Unit2;


interface


uses

Windows, SysUtils, Controls, Forms,

StdCtrls, Classes;


type

TForm1 = class(TForm)

Button1: TButton;

Edit1: TEdit;

procedure Button1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;


var

Form1: TForm1;


implementation


{$R *.dfm}


procedure TForm1.Button1Click(Sender: TObject);

type

Taddc=function(n:integer):integer;stdcall;//定义函数指针

var

Handle:Thandle;

addc:Taddc;

begin

Handle:=LoadLibrary('mydll.dll');//加载mydll

if Handle>32 then

begin

@addc:=GetProcAddress(Handle,'Tr'); //取Tr函数入口地址,大小写敏感。Tr为mydll中的Triple的exports 的name命名

if @addc<>nil then

begin

edit1.Text:=IntToStr(addc(10));//参数传递,这里直接用10

end;

end;

Freelibrary(Handle);//从内存释放dll

end;


end.



[解决办法]
应该和0比较就可以不等于0就代表加载成功
If the function succeeds, the return value is a handle to the module.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.
if @addc<>nil then。。 这个也迷糊
就是判断动态取到的函数地址是否为空,就相当于取得函数的地址,然后再用该函数的指针对该函数进行调用,你可以参考回调函数,是类似的用法
[解决办法]
简单地说,就是判断你的DLL是否加载成功,然后判断函数调用是否成功。

这些条件都具备了就赋值求解。

读书人网 >.NET

热点推荐