Error in Delphi loadlibrary ()

I let my program user select a dll from the openfile dialog (so that my user can download DLL files from my site and use it in the main project). everything works fine, and may even find out that the DLL was provided by me or an invalid dll.but was selected, the problem occurs if the user selects a renamed file (for example: apple.txt file renamed to apple.dll). I typed code like this

try dllHandle: = LoadLibrary (pwidechar (openfiledialog1.filename));

gate valve {showmessage, if it is not a dll (but it can be any DLL, it checks that it is my dll or a third party later)}

end;

the error message shown by delphi is a "bad library image"

but the catch attempt does not work, if the user selects an invalid dll, he displays his own error message and is encrypted.

Can someone help me, I'm using delphi 2009

+3
source share
1 answer

There is no exception to catch, because the exception does not occur when it LoadLibraryfails; it just returns "0".

You should check if "dllHandle" is 0 or not, if so, show the user error information using GetLastErroras documented. Alternatively, you can use the function Win32Checkin RTL, which will throw an exception with the corresponding error message:

( edit: "LoadLibrary" , : To enable or disable error messages displayed by the loader during DLL loads, use the SetErrorMode function. , , , LoadLibrary.)

var
  dllHandle: HMODULE;
  ErrorMode: UINT;
begin
  if OpenDialog1.Execute then begin
    ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); // disable OS error messages
    try
      dllHandle := LoadLibrary(PChar(OpenDialog1.FileName));
    finally
      SetErrorMode(ErrorMode);
    end;
    if Win32Check(Bool(dllHandle)) then begin  // exception raised if false
      // use the libary

      end;
  end;
end;
+11

Source: https://habr.com/ru/post/1769702/


All Articles