Dynamic-link library
동적 링크 라이브러리(영어: dynamic-link library, DLL)는 마이크로소프트 윈도에서 구현된 동적 라이브러리이다. 내부에는 다른 프로그램이 불러서 쓸 수 있는 다양한 함수들을 가지고 있는데, 확장DLL인 경우는 클래스를 가지고 있기도 한다. DLL은 COM을 담는 그릇의 역할도 한다.
사용하는 방법에는 두 가지가 있는데,
- 묵시적 링킹(Implicit linking) : 실행 파일 자체에 어떤 DLL의 어떤 함수를 사용하겠다는 정보를 포함시키고 운영체제가 프로그램 실행 시 해당 함수들을 초기화한 후 그것을 이용하는 방법과,
- 명시적 링킹(Explicit linking) : 프로그램이 실행 중일 때 API를 이용하여 DLL 파일이 있는지 검사하고 동적으로 원하는 함수만 불러와서 쓰는 방법이 있다.
전자의 경우는 컴파일러가 자동으로 해주는 경우가 많으며, 후자의 경우는 사용하고자 하는 DLL이나 함수가 실행 환경에 있을지 없을지 잘 모르는 경우에 사용된다. (때때로 메모리 절약을 위해 쓰이기도 한다.)
Categories
Simple example
간단한 DLL 사용방법은 아래와 같다. (참고로 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; 공유 라이브러리의 로드 시점 재배치(Relocation)에 관한 내용을 정리)
Favorite site
- Wikipedia (en) DLL에 대한 설명
- 간단한 DLL 작성방법
- DLL을 만들때의 추천 습관 (DLLMain deadlock 회피) 1
- [추천] A dynamic linker murder mystery
References
-
Dllmain_evasion_deadlock.zip ↩