Dynamic Link Libraries (DLLs)

How to dynamically connect a DLL in C++?

Author: Nofate, 2016-05-10

2 answers

Use the search and find the answers. For example:

  1. Working with dynamic link libraries (DLLs)
  2. Using a DLL in a Visual C++program

Implicit connection

This is the simplest method of connecting a DLL to a program. All that what is needed is to pass the name of the import library to the linker so that it can use it during the build process. There are various ways to do this.

First of all, you can directly add the MyDLL.lib file to the project using the command Project->Add to project->Files... Secondly, you can specify the name of the import library in the linker options. To do this, open project settings window (Project->Settings...) and add to the field Object/Library modules on the Link tab, name MyDLL.lib. Finally, you can embed the link to the import library directly into the program source code. To do this, use the #pragma directive with the key comment.

#pragma comment(lib,"MyDll.lib")

Explicit connection

When explicitly connecting a DLL, the programmer must take care of loading the library before using it. To do this, use the LoadLibrary function, which gets the library name and returns its handle. 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");
 9
Author: Denis Bubnov, 2016-05-10 09:24:20

Example -- in the emulator, I decided to put the screen rendering function in 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 the 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"
}

The actual rendering:

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;
}
 2
Author: nzeemin, 2016-05-10 09:51:32