Dynamic-link library
lastmod 2021-03-23created 2015-03-126 edits
A dynamic-link library (DLL) is a dynamic library implemented in Microsoft Windows. It contains various functions that other programs can call and use, and in the case of an extension DLL it may also contain classes. A DLL also serves as a container for COM.
There are two ways to use one:
- Implicit linking: the executable itself includes information about which functions of which DLL it will use, and the operating system initializes those functions when the program runs and then uses them; and
- Explicit linking: while the program is running, it uses an API to check whether the DLL file exists and dynamically loads and uses only the functions it wants.
The former is often handled automatically by the compiler, and the latter is used when it is unclear whether the DLL or function you want to use will be present in the runtime environment. (It is sometimes also used to save memory.)
Categories
Simple example
A simple way to use a DLL is shown below. (For reference, this is sample code for Visual Studio.)
DLL IMPORT
#include <stdio.h>
#include <windows.h>
#define EXPORT extern "C" __declspec(dllexport)
// DLL을 로드한 곳에서 EXPORT한 함수명을 쓸수있게 함
EXPORT int APlusB(int nA, int nB);
EXPORT int AMinusB(int nA, int nB, int& nVal);
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;
}
EXPORT int APlusB(int nA, int nB)
{
return nA + nB;
}
EXPORT int AMinusB(int nA, int nB, int& nVal)
{
if(nA > nB)
{
nVal = nA - nB;
return TRUE;
}
else
return FALSE;
}
DLL EXPORT
#include <stdio.h>
#include <windows.h>
// DLL에서 호출할 함수의 형
typedef int (*APlusB)(int, int);
typedef int (*AMinusB)(int, int, int&);
int main()
{
HINSTANCE hInst;
APlusB fAPlusB;
AMinusB fAMinusB;
// DLL 로드
hInst = LoadLibrary("SmallDll.dll");
if(hInst == NULL)
return 1;
// 호출한 함수를 맵핑
fAPlusB = (APlusB)GetProcAddress(hInst, "APlusB");
fAMinusB = (AMinusB)GetProcAddress(hInst, "AMinusB");
int nA = 700;
int nB = 200;
int nRet = 0;
int nRetVal = 0;
nRet = fAPlusB(nA, nB);
printf("%d + %d = %d\n",nA, nB, nRet);
nRet = fAMinusB(nA, nB, nRetVal);
if(nRet)
printf("%d - %d = %d\n",nA, nB, nRetVal);
else
printf("%d < %d \n",nA, nB);
// DLL 언로드
FreeLibrary(hInst);
return 0;
}
See also
- Shared Library
- Relocation (Load-time relocation of shared libraries; notes on load-time relocation of shared libraries)
Favorite site
- Wikipedia (en) article on DLL
- How to write a simple DLL
- Recommended habits when making a DLL (avoiding DLLMain deadlock) 1
- [Recommended] A dynamic linker murder mystery
References
-
Dllmain_evasion_deadlock.zip ↩
Pages that link here