在DLL中代码怎样动态获得所在DLL的名称?

解决方案 »

  1.   


    DLL中调用GetModuleFileName(NULL)得到的是DLL被调用的EXE的名称;
    GetModuleFileName(GetModuleFileName(NULL))也是所在EXE的名称;
    给出这两个函数的中文参数详细说明也可以得部分分(先有鸡还是先有蛋的问题):
    GetModuleHandle
    GetModuleFileName
      

  2.   

    //上面写错了一点,更正:GetModuleFileName(GetModuleHandle(NULL))我想到的一种方法是:
       1.在DLL的代码中获得当前被执行的代码所在的地址p
       2.得到整个进程的模块分布区间
       3.查询地址p属于哪一个模块区间内
       4.得到所在区间模块的基地址d
       5.GetModuleFileName(d);  太麻烦了!
      

  3.   

    DllMain()函数中有一个HINSTANCE hInstance,这就是这个Dll的Handle,
    VC的扩展DLL中使用了static AFX_EXTENSION_MODULE xxxDLL = { NULL, NULL };来记录动态库的Moudle和Resource Handle
    new CDynLinkLibrary(ECadObjectsDLL);
    char szFile[512];
    GetModuleFileName(xxxDll.hModule, szFile, 512);
      

  4.   

    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
    }
      

  5.   

    to: luogucai(萝卜)
      我的代码中没有办法获得DllMain()函数中的HINSTANCE hInstance
      下面的代码执行也不正确:
      AFX_EXTENSION_MODULE ECadObjectsDLL;
      new CDynLinkLibrary(ECadObjectsDLL);
      char szFile[512];
      GetModuleFileName(ECadObjectsDLL.hModule, szFile, 512);
      

  6.   

    to: approach()    谢谢,你的方法测试通过;
      

  7.   

    VirtualQuery这个函数居然没有查到
    再次谢谢approach
    结帖