How to dynamically define member functions in C++
It's simple enough to factor out the logic into a function template:
template <class Function, class... Args>
decltype(auto) getProcAddressAndCall(
Function *&function,
char const *name,
Args &&... args
) {
if(!function)
function = reinterpret_cast<Function *>(GetProcAddress(HMODULEDLL, name));
return function(std::forward<Args>(args)...);
}
... which you can then call with:
ResultType Wrapper::pertainingMemberFunction(...)
{
return getProcAddressAndCall(pointerToPertainingDLLFunction, "pertainingName", ...);
}
The other solutions all are reasonable approached, but pretty complex.
It turns out you can get a lot more help from Visual Studio. The reason is that your behavior closely aligns with a Visual Studio feature, delay-loaded DLL's. Visual Studio's implementation of delay-loaded DLL's works by generating GetProcAddress
calls for all the functions of a DLL, which is exactly what you need.
Now it appears that your specific functionality is to read a registry key to find the specific DLL. As it happens, the delay-loading mechanism has a hook mechanism. If you define __pfnDliNotifyHook2
, it gets called with notification dliNotePreLoadLibrary
just before LoadLibrary
would be called.
Your hook function can substitute its own LoadLibrary
function instead, and load the DLL from the desired location. Just return the HMODULE
and Visual Studio will use that for its generated GetProcAddress
calls.
So, your resulting solution looks like this:
ResultType Wrapper::DllFunction(...)
{
return DLLFunction (...);
}
Simple, isn't it? Visual Studio will notice that DllFunction
comes from a delay-loaded DLL and insert the GetProcAddress
call, using the HMODULE
from your __pfnDliNotifyHook2
.