How to dynamically connect a DLL in C ++?
2 answers
Use the search and find the answers. For example:
Implicit connection
This is the easiest method of connecting a DLL to a program. All you need to do is pass the name of the import library to the linker so that it uses it during the build process. This can be done in various ways.
Firstly, you can directly add the MyDll.lib file to the project using the Project-> Add to project-> Files command ... Secondly, you can specify the name of the import library in the linker options. To do this, open the project settings window ( Project-> Settings ...) and add the name MyDll.lib in the Object / Library modules field on the Link tab. Finally, you can embed a link to the import library directly into the source code of the program. The directive #pragma with the comment key is used for this.
#pragma comment(lib,"MyDll.lib") Explicit connection
When DLL is explicitly connected, the programmer must take care of loading the library before using it. To do this, use the LoadLibrary function, which takes the name of the library and returns its descriptor. The handle must be stored in a variable, since it will be used by all other functions designed to work with the DLL.
HMODULE hLib; hLib = LoadLibrary("MyDll.dll"); Example - in the emulator, I decided to move the screen drawing function to a separate DLL.
Declarations and variables:
typedef void (CALLBACK* RENDER_DRAW_CALLBACK)(const void * pixels, HDC hdcTarget); HMODULE g_hModuleRender = NULL; RENDER_DRAW_CALLBACK RenderDrawProc = NULL; At the beginning of work:
g_hModuleRender = ::LoadLibrary(szRenderLibraryName); if (g_hModuleRender == NULL) { //TODO: Отрабатываем ситуацию "не смогли загрузить DLL", показываем ::GetLastError() } RenderDrawProc = (RENDER_DRAW_CALLBACK) ::GetProcAddress(g_hModuleRender, "RenderDraw"); if (RenderDrawProc == NULL) { //TODO: Отрабатываем ситуацию "не смогли получить адрес функции из DLL" } Actually drawing:
void ScreenView_OnDraw(HDC hdc) { if (RenderDrawProc != NULL) { RenderDrawProc(m_bits, hdc); } } At the end of the work:
if (g_hModuleRender != NULL) { RenderDrawProc = NULL; ::FreeLibrary(g_hModuleRender); g_hModuleRender = NULL; }