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一定要在同一目录下.



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