- 1 year ago
Delay-load DLL in windows: can I dynamically choose what DLL name to look for? (c++)
In Windows, when using delay-loaded DLLs, the DLL name is typically specified at compile-time and cannot be dynamically chosen at runtime. The DLL name is resolved during the build process and embedded in the executable.
However, if you need the ability to dynamically choose the DLL name to look for at runtime, you can use a different approach, such as dynamic loading of DLLs using explicit function calls.
Here's an example of how you can dynamically load a DLL and call functions from it at runtime in C++:
cpp#include <iostream>
#include <windows.h>
typedef int (*MyFunctionType)(int); // Define the function signature
int main() {
HMODULE dllHandle = LoadLibrary("your_dll_name.dll"); // Load the DLL dynamically
if (dllHandle != nullptr) {
MyFunctionType myFunction = reinterpret_cast<MyFunctionType>(GetProcAddress(dllHandle, "YourFunctionName")); // Get the function pointer
if (myFunction != nullptr) {
// Call the function dynamically
int result = myFunction(42);
std::cout << "Result: " << result << std::endl;
} else {
std::cerr << "Failed to get function address" << std::endl;
}
FreeLibrary(dllHandle); // Release the DLL
} else {
std::cerr << "Failed to load DLL" << std::endl;
}
return 0;
}
In this example, the DLL is dynamically loaded using LoadLibrary
, and the function address is obtained using GetProcAddress
. You can replace "your_dll_name.dll"
with the desired DLL name, and "YourFunctionName"
with the name of the function you want to call from the DLL.
With this approach, you have the flexibility to dynamically choose the DLL name at runtime and call the desired functions. Note that you need to ensure that the DLL is available at the specified location or within the system's search path.