如何在DLL中,获取DLL本身的路径以及调用DLL的文件的路径呢?主要通过GetModuleFileName(HMODULE
hModule,
LPTSTR
lpFilename,
DWORD
nSize)
函数来获取,根据hModule参数来辨别是DLL本身还是DLL的调用者。
当hModule 为NULL时候 获取到路径为调用者,当hModule为main入口的
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
中的hModule的时候,获取到的路径是DLL本身的路径。实例效果如下:
DLL文件的核心代码如下:
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { TCHAR pCallFileName[MAX_PATH]; TCHAR pDllFileName[MAX_PATH]; ::GetModuleFileName(NULL,pCallFileName,MAX_PATH); ATL::CString strCall = pCallFileName; strCall = L"调用EXE:" + strCall; ::GetModuleFileName(hModule,pDllFileName,MAX_PATH); ATL::CString strTips = pDllFileName; strTips = L"被调用DLL:"+strTips; ::MessageBox(NULL,strCall+L" "+strTips,L"MyDLL.dll",MB_OK); 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文件的程序调用DLL代码如下:
//静态库调用 #include "../LibTest/lib.h" #pragma comment(lib,"../release/LibTest.lib")//指定与静态库一起链接 //dll 的静态调用 #pragma comment(lib,"../release/MyDLL.lib") extern "C" _declspec(dllexport) int sub(int x,int y); //dll的动态调用 typedef int(*lpSubFun)(int,int);//宏定义函数指针类型 int _tmain(int argc, _TCHAR* argv[]) { //静态库调用 //int rs = add(5,10); //cout << rs <<endl; //dll的静态调用 //int rs2 = sub(100,33); //cout << rs2 <<endl; //dll的动态调用: LoadLibrary-GetProcAddress-FreeLibrary” //系统Api提供的三位一体“DLL加载-DLL函数地址获取-DLL释放”方式 HINSTANCE hDll;//DLL句柄 lpSubFun subFunc;//函数指针 hDll = LoadLibrary(L"../release/MyDLL.dll"); if(hDll!=NULL) { subFunc = (lpSubFun)GetProcAddress(hDll,"sub"); } if(subFunc!=NULL) { int rs3 = sub(100,88); //cout << rs3 << endl; } //cin.get(); return 0; }