动态加载DLL 为什么小弟我这样报错
动态加载DLL 为什么我这样报错?
type
Tmsg=function (hWnd: HWND; lpText, lpCaption: PChar; uType: UINT): Integer; stdcall;
@Mymsg:=GetProcAddress(LoadLibrary(pchar('user32.dll')),pchar('MessageBoxA'));
Mymsg(0, PChar('TempStr'), PChar('TempStr1'), MB_YESNOCANCEL);
按照这样做 运行下来没问题
但是我现在有很多函数需要动态加载 而且不止一个DLL文件
所以为了减少冗余代码 我写了个函数
function LoadDll(DllName:string; ProcAdr:pointer; FunctionName:string):boolean;
var
Dlllhandle:Thandle;
begin
result:=true;
DlllHandle:=LoadLibrary(pchar(DllName));
if DlllHandle = 0 then begin result:=false; exit; end;
ProcAdr:=GetProcAddress(DlllHandle,pchar(FunctionName));
if not Assigned(ProcAdr) then result:=false;
end;
调用的时候
LoadDll('user32.dll'',@Mymsg,'MessageBoxA');
Mymsg(0, PChar('TempStr'), PChar('TempStr1'), MB_YESNOCANCEL);
这样就报错了
问题出在哪里 应该怎么改正
------解决方案--------------------
function LoadDll(DllName:string; ProcAdr:pointer; FunctionName:string):boolean;改为function LoadDll(DllName:string; var ProcAdr:pointer; FunctionName:string):boolean;
变量参数的问题。。
------解决方案--------------------
type
Tmsg=function (hWnd: HWND; lpText, lpCaption: PChar; uType: UINT): Integer; stdcall;
@Mymsg:=GetProcAddress(LoadLibrary(pchar('user32.dll')),pchar('MessageBoxA'));
Mymsg(0, PChar('TempStr'), PChar('TempStr1'), MB_YESNOCANCEL);
按照这样做 运行下来没问题
但是我现在有很多函数需要动态加载 而且不止一个DLL文件
所以为了减少冗余代码 我写了个函数
function LoadDll(DllName:string; ProcAdr:pointer; FunctionName:string):boolean;
var
Dlllhandle:Thandle;
begin
result:=true;
DlllHandle:=LoadLibrary(pchar(DllName));
if DlllHandle = 0 then begin result:=false; exit; end;
ProcAdr:=GetProcAddress(DlllHandle,pchar(FunctionName));
if not Assigned(ProcAdr) then result:=false;
end;
调用的时候
LoadDll('user32.dll'',@Mymsg,'MessageBoxA');
Mymsg(0, PChar('TempStr'), PChar('TempStr1'), MB_YESNOCANCEL);
这样就报错了
问题出在哪里 应该怎么改正
------解决方案--------------------
function LoadDll(DllName:string; ProcAdr:pointer; FunctionName:string):boolean;改为function LoadDll(DllName:string; var ProcAdr:pointer; FunctionName:string):boolean;
变量参数的问题。。
------解决方案--------------------
- Delphi(Pascal) code
function LoadDll(DllName:string;var ProcAdr:pointer; FunctionName:string):boolean; var Dlllhandle:Thandle; begin result:=false; DlllHandle:=LoadLibrary(pchar(DllName)); if DlllHandle = 0 then exit; ProcAdr:=GetProcAddress(DlllHandle,pchar(FunctionName)); result:= Assigned(ProcAdr); end; procedure TForm1.Button2Click(Sender: TObject); begin if LoadDll('user32.dll',@Mymsg,'MessageBoxA') then Mymsg(0, PChar('TempStr'), PChar('TempStr1'), MB_YESNOCANCEL); end;
------解决方案--------------------
而且你想在什么地方FreeLibrary呢?一般来说,用完一个dll函数就得释放dll
------解决方案--------------------
DLL引用方式有两种:
静态加载DLL,就是程序运行时就加载DLL,直到关闭程序时才释放DLL
动态加载DLL,程序在使用时才加载DLL