Can Delphi use a DLL if required?

I added these two methods to the 1st block of my Delphi 5 application.

function Inp(PortAddress: Integer): Integer; stdcall; external 'inpout32.dll' name 'Inp32'; procedure Output(PortAddress, Value: Integer); stdcall; external 'inpout32.dll' name 'Out32'; 

However, I do not want to release the inpout32 library with software if they are clearly not needed. The program currently says β€œNot Found” at runtime if they are not present in the root or System32.

Users will only call these methods if they have a specific set of parameters, but this is not collected from the .ini file until the inpout library is used.

Is there a way to use this library if necessary, as some components do, rather than declaring it the way I do?

+6
source share
2 answers

In versions of Delphi prior to 2010, you must use classic dynamic loading. Consider this typical (and simple) example calling the Beep function of Kernel32.dll (which you, of course, should not hardcode the path in real code!):

 type TBeepFunc = function(dwFreq: DWORD; dwDuration: DWORD): BOOL; stdcall; procedure TForm4.FormClick(Sender: TObject); var lib: HMODULE; prc: TBeepFunc; begin lib := LoadLibrary('C:\WINDOWS\System32\Kernel32.dll'); if lib = 0 then RaiseLastOSError; try @prc := GetProcAddress(lib, 'Beep'); if Assigned(prc) then prc(400, 2000) else ShowMessage('WTF? No Beep in Kernel32.dll?!'); finally FreeLibrary(lib); end; end; 
+15
source

This feature, known as download latency , was added in Delphi 2010.

Using your code as an example, you can write your import as follows:

 function Inp(PortAddress: Integer): Integer; stdcall; external 'inpout32.dll' name 'Inp32' delayed; 

Linking to this external function will only be performed the first time the function is called. If the binding fails, an exception occurs at run time.

You can use SetDliNotifyHook and SetDliFailureHook to customize the delay loading behavior if you need even more fine-grained control.

Some blog articles that complement the product documentation:


In older versions of Delphi, you can use LoadLibrary and GetProcAddress . Or, if you want to smooth things out a bit, I can heartily recommend the Hallvard Vassbotn delay loading class, which he describes in this blog post . This code wraps all the boiler plates when calling LoadLibrary and GetProcAddress and is only slightly more cumbersome to use than the new built-in Delphi 2010 function.

I have successfully used the Hallvard library for many years. One minor word of caution is that it is not thread safe, so if multiple threads try to associate with a function at the same time, then the code may fail. This is easy enough to fix by adding internal locks to Hallvard code.

+16
source

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


All Articles