访问dll中的例程,有两种方式:静态引入方式和动态引入方式。
静态方式:在单元的interface部分用external列出要从dll中引入的例程。
动态方式:调用windows的api函数LoadLibrary(LoadLibraryEx),GetProceAddress,FreeLibrary
例如:
如果你调用DLLName.dll 中一个名为functionName的函数,可以这样写:
type
TFunctionName=function(参数列表):返回类型;stdcall;procedure TForm1.Button1Click(Sender:TObject);
var
LibHandle:THandle;
FunctionName=TFunctionName;
begin
LibHandle:=LoadLibrary('DLLName.dll');
try
if LibHandle=0 then
raise Exception.create('unable to load dll');
@FunctionName:=GetProcAddress(LibHandle,'FunctionName');
if not (@FunctionName=nil) then
.....
else
.....
finally
FreeLibrary(LibHandle);
end;
end;
静态方式:在单元的interface部分用external列出要从dll中引入的例程。
动态方式:调用windows的api函数LoadLibrary(LoadLibraryEx),GetProceAddress,FreeLibrary
例如:
如果你调用DLLName.dll 中一个名为functionName的函数,可以这样写:
type
TFunctionName=function(参数列表):返回类型;stdcall;procedure TForm1.Button1Click(Sender:TObject);
var
LibHandle:THandle;
FunctionName=TFunctionName;
begin
LibHandle:=LoadLibrary('DLLName.dll');
try
if LibHandle=0 then
raise Exception.create('unable to load dll');
@FunctionName:=GetProcAddress(LibHandle,'FunctionName');
if not (@FunctionName=nil) then
.....
else
.....
finally
FreeLibrary(LibHandle);
end;
end;
如function IsWindow(hWnd: HWND): BOOL; stdcall; external 'user32.dll;
在程序启动时调用该dll,缺点是调用失败,程序就不能运行
而动态调用就没有这个缺点
如
type
TIsWindow=function (hWnd:HWND): BOOL; stdcall;
IsWindow:TIsWindow;
hModule:=LoadLibrary("user32.dll")
@IsWindow:=GetProcAddress(hModule,'IsWindow');
这样就可以调用,可以根据hModule的值来判断dll是否装载成功