June 29, 2013

Delayed loading of a DLL

The delayed directive can be used when declaring a function exported from a DLL so that the DLL is not loaded before the function is called.

This is very useful because you may first check if the conditions are met to call the DLL before actually loading the DLL, for example check if the DLL is located where it should.

If you statically load a DLL (the default), then your application won’t start if the DLL is not present. You could as well dynamically load the DLL (LoadLibrary) to avoid this issue, but it is a little bit more work for you to declare function pointer and the get each function address (GetProcAddress) by code. Using delayed directive is much easier. Just add delayed keyword in each function declaration and suddenly a static DLL is loaded the first time one of his functions is called. If you never call a DLL’s function, then the DLL is not loaded at all.

A declaration looks like this:
    function GetSomething: Integer; external 'somelibrary.dll' delayed;

This directive exists since Delphi 2010. There is valuable documentation on Embarcadero DocWiki at this URL: http://docwiki.embarcadero.com/RADStudio/XE4/en/Libraries_and_Packages#Delayed_Loading And you can find some code sample here: http://docwiki.embarcadero.com/CodeExamples/XE4/en/DelayedLoading_(Delphi)

Follow me on Twitter
Follow me on LinkedIn
Follow me on Google+
Visit my website: http://www.overbyte.be

6 comments:

Leonardo M. Ramé said...

Nice to know this. Good bye to GetProcAddress.

Alexandre Caldas Machado said...

Nice tip!
When you say "Just add delayed keyboard in each function" I guess you mean "Just add delayed keyword"...

François Piette said...

Typo fixed. Thanks.

Eric said...

On the other hand, this only goes half-way of dynamic loading, f.i. when functions are only supported on certain versions of a DLL, delayed becomes more complex to use without crashes. Another issue with delayed is that you don't have control over which DLL is actually going to be used, unlike LoadLibrary.

Eric said...

On the other hand, this only goes half-way of dynamic loading, f.i. when functions are only supported on certain versions of a DLL, delayed becomes more complex to use without crashes. Another issue with delayed is that you don't have control over which DLL is actually going to be used, unlike LoadLibrary.

Dave said...

It's worth noting this is actually a feature ported over from C++ Builder, which has had it for some time. (C++ Builder 6? I'm not sure.) You can specify a DLL name in the project options, and all functions in it will be delay-loaded.

In a way, this is simpler than a keyword per function, although it does mean that you can't mix normally linked and delay-loaded functions from the one DLL. I believe Delphi uses this for, eg, new functions from kernel32 etc, which you couldn't do with the C++ version.