Most DLL developers have faced the challenge of detecting a HMODULE/HINSTANCE handle within the module you're running in. It may be a difficult task if you wrote the DLL without a DLLMain() function or you are unaware of its name. For example:Your DLL was built without ATL/MFC, so the DLLMain() function exists, but it's hidden from you code and you cannot access the hinstDLL parameter. You do not know the DLL's real file name because it could be renamed by everyone, so GetModuleHandle() is not for you.This small code can help you solve this problem:#if _MSC_VER >= 1300 // for VC 7.0 // from ATL 7.0 sources #ifndef _delayimp_h extern "C" IMAGE_DOS_HEADER __ImageBase; #endif #endifHMODULE GetCurrentModule() { #if _MSC_VER < 1300 // earlier than .NET compiler (VC 6.0) // Here's a trick that will get you the handle of the module // you're running in without any a-priori knowledge: // http://www.dotnet247.com/247reference/msgs/13/65259.aspx MEMORY_BASIC_INFORMATION mbi; static int dummy; VirtualQuery( &dummy, &mbi, sizeof(mbi) ); return reinterpret_cast<HMODULE>(mbi.AllocationBase);#else // VC 7.0 // from ATL 7.0 sources return reinterpret_cast<HMODULE>(&__ImageBase); #endif }
to: luogucai(萝卜) 我的代码中没有办法获得DllMain()函数中的HINSTANCE hInstance 下面的代码执行也不正确: AFX_EXTENSION_MODULE ECadObjectsDLL; new CDynLinkLibrary(ECadObjectsDLL); char szFile[512]; GetModuleFileName(ECadObjectsDLL.hModule, szFile, 512);
DLL中调用GetModuleFileName(NULL)得到的是DLL被调用的EXE的名称;
GetModuleFileName(GetModuleFileName(NULL))也是所在EXE的名称;
给出这两个函数的中文参数详细说明也可以得部分分(先有鸡还是先有蛋的问题):
GetModuleHandle
GetModuleFileName
1.在DLL的代码中获得当前被执行的代码所在的地址p
2.得到整个进程的模块分布区间
3.查询地址p属于哪一个模块区间内
4.得到所在区间模块的基地址d
5.GetModuleFileName(d); 太麻烦了!
VC的扩展DLL中使用了static AFX_EXTENSION_MODULE xxxDLL = { NULL, NULL };来记录动态库的Moudle和Resource Handle
new CDynLinkLibrary(ECadObjectsDLL);
char szFile[512];
GetModuleFileName(xxxDll.hModule, szFile, 512);
// from ATL 7.0 sources
#ifndef _delayimp_h
extern "C" IMAGE_DOS_HEADER __ImageBase;
#endif
#endifHMODULE GetCurrentModule()
{
#if _MSC_VER < 1300 // earlier than .NET compiler (VC 6.0) // Here's a trick that will get you the handle of the module
// you're running in without any a-priori knowledge:
// http://www.dotnet247.com/247reference/msgs/13/65259.aspx MEMORY_BASIC_INFORMATION mbi;
static int dummy;
VirtualQuery( &dummy, &mbi, sizeof(mbi) ); return reinterpret_cast<HMODULE>(mbi.AllocationBase);#else // VC 7.0 // from ATL 7.0 sources return reinterpret_cast<HMODULE>(&__ImageBase);
#endif
}
我的代码中没有办法获得DllMain()函数中的HINSTANCE hInstance
下面的代码执行也不正确:
AFX_EXTENSION_MODULE ECadObjectsDLL;
new CDynLinkLibrary(ECadObjectsDLL);
char szFile[512];
GetModuleFileName(ECadObjectsDLL.hModule, szFile, 512);
再次谢谢approach
结帖