We only need .dll and header
Creating a Project Using a DLL
This time, our project properties don’t need any additional settings. Just make sure the .dll and our .exe are placed in the same directory, and we can include the corresponding header file.
However, we need to follow these steps:
- Include Header File: Include the header file defined in the DLL so that your program knows the functions, structures, or classes provided by the DLL.
- Load the DLL: Use the LoadLibrary function in the code to load the DLL and obtain a handle (HINSTANCE) representing the DLL.
- Get Function Pointer: Use the GetProcAddress function to get the pointer to the desired function from the DLL. You need to know the name of the function in the DLL and the type of its function pointer.
- Use Function Pointer: Use the obtained function pointer just like a regular function pointer to call functions from the DLL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <Windows.h> // Include Windows API library
#include "../Dll1/MyDLL.h" // Include header file from DLL
// Function pointer type for pointing to the Add function in the DLL
typedef int(*AddFunc)(int, int);
int main()
{
// Load DLL
HINSTANCE hDLL = LoadLibrary(TEXT("Dll1.dll"));
if (hDLL == NULL) {
std::cerr << "Failed to load DLL." << std::endl;
return 1;
}
// Get function pointer from DLL
AddFunc addFunc = (AddFunc)GetProcAddress(hDLL, "AddFunction");
if (addFunc == NULL) {
std::cerr << "Failed to get function pointer." << std::endl;
return 1;
}
// Use function from DLL
int result = addFunc(3, 4);
std::cout << "Result of Add(3, 4): " << result << std::endl;
// Use MyStruct defined in DLL
MyStruct myStruct{ 1,5 };
std::cout << "Use MyStruct in DLL : " << myStruct.number1 << std::endl;
std::cout << "Use MyStruct in DLL : " << myStruct.number2 << std::endl << std::endl;
// Call AddTemplate function template from DLL
std::cout << "Call AddTemplate in DLL : " << AddTemplate(1.1, 2.3) << std::endl << std::endl;
// Unload DLL
FreeLibrary(hDLL);
return 0;
}
Folder
Using ‘LoadLibrary’ to load the DLL
Before loading the module
After loading the module
Result





