Home >Backend Development >C++ >How Can I Dynamically Load and Use Functions from a DLL in C ?
Dynamic linking allows you to load a function from a DLL during runtime, extending the functionality of your program. This article will guide you on how to accomplish this.
The first step is to load the DLL into the memory of the current process. This is done using the LoadLibrary function:
HINSTANCE hGetProcIDDLL = LoadLibrary("path/to/test.dll");
Once the DLL is loaded, you need to locate the address of the function you want to call. For this, we use the GetProcAddress function:
typedef int (__stdcall *f_funci)(); f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
Note that you need to define a function pointer type that matches the signature of the exported function. In our case, it's a function returning an integer and taking no arguments.
For the DLL to be loaded successfully, you need to export the function correctly. Add the following to your DLL's source code:
int __declspec(dllexport) __stdcall funci() { // ... }
Once the function's address is obtained, you can call it like any other function:
std::cout << "funci() returned " << funci() << std::endl;
For resource cleanup, it's good practice to release the DLL handle when not needed anymore:
FreeLibrary(hGetProcIDDLL);
By following these steps, you can dynamically load and use functions from DLLs, significantly enhancing the flexibility and extensibility of your program.
The above is the detailed content of How Can I Dynamically Load and Use Functions from a DLL in C ?. For more information, please follow other related articles on the PHP Chinese website!