VC6.0에서 DLL을 만들고 Load 해서 함수 사용하기… (연습)
1. DLL을 만들기..
VC6.0실행하고 새로운 파일 만들기 누르면.. DLL선택하고 만들면 된다.
만든 코드에서 DLL에서 제공할 함수들을 작성해보자.
header file
=====================================================
#define SIMPLEDLL_EXPORTS
#ifdef SIMPLEDLL_EXPORTS
#define DLLFunction __declspec(dllexport) //« 이거 사용 안하면 Dll load 할때 function을 찾지 못한다. (1시간가량 헤멤)
#else
#define DLLFunction __declspec(dllimport)
#endif
#ifdef __cplusplus
extern “C” {
#endif/- __cplusplus *-
DLLFunction int DllPrintTest(char * string);
#ifdef __cplusplus
};
#endif/- __cplusplus *-
=====================================================
Dll C file.
=====================================================
#include “stdafx.h”
#include
#include “DllTest.h”
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
DLLFunction int DllPrintTest(char * string) // 별것 없고 들어온 string을 print하는 함수.
{
if(string == NULL)
return 0;
else
{
printf(“%s \n”,string);
return 1;
}
}
=====================================================
모.. DLL file을 만들면.. 잘 만들어 진다..
쓰다보니 길어지네… 한가지 더 첨부하면.
Dll의 경우 MFC library를 다 넣고 만드는 방법과 MFC library는 안넣고 만드는 방법이 있다.
Alt+F7을 눌러 Project Setting -> General -> Microsoft Foundation Classers에
Use MFC in a Static Library를 선택하면 MFC library를 모두 포함해서 만들므로 MFC가 안깔려 있어도 잘 된다.
Use MFC in a Share DLL을 선택할 경우 MFC Library를 포함하지 않기 때문에 MFC가 안깔려 있다면 빌드가 안된다.
이점도 나중에 혹시 필요할지 모르지 주지 하겠다 ^^;
2. Dll을 로드 하기…
Dll의 경우 링크시 아래 두가지 방식을 사용 할수 있다.
- Implict 링크
-
Dll, header, lib 파일이 필요함.
-
extern “C” __declspec(dllimport) int function(int n); 이런식으로 extern을 하면 됨.
2. Explicit 링크 « 필자는 이 방식으로 아래 예제를 만듬.
- DLL만 필요하다. 단 아래 두가지 함수가 호출되어야 한다.
#include
HINSTANCE LoadLibrary(“Dll file name”);
GetProcAddress(Dll handle,”function name”);
다 사용후 FreeLibrary(Dll handle)을 써야함.
100문이 불여일견이라.. Library Load 및 function사용한 예를 보자… (위에 있는 Dll을 로드해서 사용한 예제임)
==========================================================
#include
**#include
void main(void)
{
char * temp = “TESTDLL”;
HINSTANCE hDll; //hDll function handler를 선언한다.
hDll = LoadLibrary(“DllTest”); // DllTest.dll 파일을 찾아서 hDll handler로 연결함.
if(hDll != NULL)
{
typedef int (*DllTest)(char * string); //함수 포인터 생성. 함수 원형은 int DllPrintTest(char * string)임
DllTest DllPrintfunction; //DllPrintfunction 함수 선언.
DllPrintfunction = (DllTest)GetProcAddress(hDll,”DllPrintTest”); //DllPrintTest 함수를 DllPrintfunction으로 멥핑
if(DllPrintfunction != NULL)
DllPrintfunction(temp); // DllPrintTest를 실행함.
FreeLibrary(hDll); // 열어 놓은 헨들러를 닫음.
}
}
==========================================================
와우.. Dll을 debug mode로 빌드를 하면 Dll 로드한 곳에서 디버깅하게되면 관련 함수까지 따라 들어갈수 있다.
release mode로 빌드하게 되면 Dll 로드한 곳에서 함수 디버깅은 불가능 하군.
이것참.. 재미있는데 ^^;