Reputation: 329
I am looking for a clean way to explicitly load library. Most often, I have a LIB and DLL pair so the LIB will handle all the "load stuff" and I can directly call the function in the dll. When doing this explicitly, I need to do sort of the following:
HMODULE libA = LoadLibrary("dllA.dll"); // NULL if load failed
HMODULE libB = LoadLibrary("dllB.dll"); // NULL if load failed
void (*functionA)(void) = libA ? GetProcAddress(libA,"functionA"):NULL;
void (*functionB)(void) = libB ? GetProcAddress(libB,"functionB"):NULL;
It will be messy if the LoadLibrary() and GetProcAddress() are found all over my code when I need to call function in DLL. I would like to know if there is a clean way such that I can write all the handling within 1-2 files and call the functions as if I am loading the library implicitly through LIB and DLL pair.
Upvotes: 2
Views: 993
Reputation: 15355
Write a pure interface to the external functions you need. (Platform dependent)
Provide an implementation class (for you platform). For your Windows implementation load the DLL, get the procedure address initially.
Than when the interface function need to be called, the class routes the call into the loaded DLL.
Use an similar way for other platforms.
This is nothing else than using of delay-loaded DLLs. It is just a manual solution. But the approach of using an interface allows you a real platform dependent solution.
Upvotes: 0
Reputation: 51345
Indeed there is a way to get all the implicit linking convenience, while still being able to gracefully handle both library load as well as symbol lookup failures. Visual Studio offers Linker Support for Delay-Loaded DLLs, that give user code the ability to hook into the loader, and implement arbitrary recovery strategies for unavailable symbols (e.g. by returning a no-op stub). This makes it possible to consolidate all failure handling into a single place.
Upvotes: 2