I am original based on multiple related blog posts on the Internet
1) generate DLL
Create two files: XXX. H, XXX. cpp
The content of XXX. H is as follows:
# Ifdef build_xxx_dll
# Define export _ declspec (dllexport)
# Else
# Define export _ declspec (dllimport)
# Endif
Extern "C "{
Export void example (void );
......
}
The content of XXX. cpp is as follows:
# Define build_xxx_dll
# Include "XXX. H"
Void example (void)
{
}
......
Then compile from the DOS Console (assuming mingw has been installed and environment variables are added)
G ++-shared-wl, -- kill-at, -- output-def, XXX. Def-o xxx. dll XXX. cpp
(Because C ++ implements function overloading by modifying the function name, we must use extern "C" with the -- kill-at compilation option to avoid modifying the function name, build_xxx_dll macro is used to select the function prototype declaration)
2) Static Call DLL
Add the following content to the new file yyy. cpp;
# Include "XXX. H"
# Pragma comment (Lib, "XXX. dll ")
The generated DLL does not require def files or CPP files.
If XXX. H is not included, add the function prototype declaration in the H file to yyy. cpp.
You must add a DLL during compilation, as shown in the following code:
G ++-L.-O yyy.exe yyy. cpp XXX. dll
3) dynamic call of DLL
First, you need to include windows. h
# Include <windows. h>
You also need a handle to save the loaded DLL file.
Hinstance hdll = loadlibrary ("XXX. dll ");
Declare the corresponding function pointer type of the required function
Typedef void (* pfunc) (void );
Returns the pointer to a function.
Pfunc pF = (pfunc *) getprocaddress (hdll, "example ");
Release the DLL file after use.
Freelibrary (hdll );