DLL 學習心得



在VC產生的框架裏面,裏面有個.h 這個h文件可以同時被DLL工程和EXE工程使用.

關鍵巧妙的地方是DLL_XXX_EXPORTS(這裏是DLL_SAMPLE_EXPORTS)這個宏,在DLL工程裏面,這個宏

會在編譯的時候指定,所以以這個宏修飾的類/變量/函數 都會變成__declspec(dllexport),而EXE

工程沒有指定這個宏,就變成__declspec(dllimport),表示引用外部申明.

// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the DLL_SAMPLE_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// DLL_SAMPLE_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
#ifdef DLL_SAMPLE_EXPORTS
#define DLL_SAMPLE_API __declspec(dllexport)
#else
#define DLL_SAMPLE_API __declspec(dllimport)
#endif

// This class is exported from the DLL_SAMPLE.dll
class DLL_SAMPLE_API CDLL_SAMPLE {
public:
CDLL_SAMPLE(
void);
// TODO: add your methods here.
}
;

 

CPP_SWITCHES=/nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "DLL_SAMPLE_EXPORTS" /Fp"$(INTDIR)/DLL_SAMPLE.pch" /Yc"stdafx.h" /Fo"$(INTDIR)//" /Fd"$(INTDIR)//" /FD /c

DLL的框架如下:

BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}

return TRUE;
}

引用這個DLL的EXE工程可以在C裏面顯式地包含這個庫

#pragma comment(lib,"DLL_SAMPLE")

也可以在工程屬性裏面設置,效果是一樣的.

最後一點需要說明的是,產生的EXE和DLL一定要在同一目錄下.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章