parean
parean

Reputation: 305

Is it safe to mix delayed dll loading and manual call of LoadLibraryA?

I am compiling a program for windows.

I want it to check if foo.dll exists in the system, and if not, to print an error message and exit. Is it safe to do it like this:

  1. pass the /DELAYLOAD foo.dll flag to the linker;
  2. at the very beginning of the main(), manually call auto handle = LoadLibraryA("foo.dll") and check if handle is not NULL;
  3. if it's not NULL, continue to work;
  4. at the end of the main(), call FreeLibrary(handle)?

I am wondering if something will break due to mixing delayed loading and manually calling LoadLibraryA(). Also, if someone could suggest a simpler or more correct way to do what I want, I would appreciate it.

Upvotes: 3

Views: 320

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51894

If you are going to do this, you should call FreeLibrary() immediately after your 'test' call to LoadLibrary() - but certainly before you cause the auto-load by calling one of its routines! (That is, of course, assuming the call succeeded!) That way, there should be no problem with load clashes. (You could also make further tests, such as checking that all required routines are present, with calls to GetProcAddress().

Once you have verified that the DLL is present (and, obviously, loadable), you would then continue execution - the DLL will be loaded 'automatically' when your executable first calls one of its exported functions.

If you have the DLL already loaded (manually), then it will try to load itself twice into the same process (I think). This would cause problems, at some point, for sure.

PS: It's a good way to do the check, IMHO!! Please, do let us know how it fares.

EDIT: Following the (somewhat extensive) discussion in the comments, it is now clear to me that it is unnecessary to call FreeLibrary() - either when I suggested or, indeed, at the end of the program (as it will be unloaded then, anyway). But it's still a good solution!

Upvotes: 1

Related Questions