AfxLoadLibrary

使用 AfxLoadLibrary 映射 DLL 模块。

HINSTANCE AFXAPI AfxLoadLibrary( 
   LPCTSTR lpszModuleName  
);

参数

  • lpszModuleName
    指向 null 终止的字符串包含该模块的名称 ( .DLL 或 .exe 文件)。 指定名称为模块的文件名。

    如果字符串指定路径,但文件在指定的目录中不存在,则函数将失败。

    如果没有指定路径,并且文件扩展名未被提及,默认扩展名追加 .DLL。 但是,文件名字符串包括一后缀指向字符 (.)表明模块名称没有扩展名。 当未指定路径,文件的函数搜索以下序列:

    • 应用程序加载的目录。

    • 当前目录。

    • Windows 95/98: Windows 系统目录。 Windows NT: 32 位 Windows 系统目录。 此目录的名称为 SYSTEM32。

    • Windows NT only: 16 位 Windows 系统目录。 没有获得此目录路径的 Win32 函数,但是它已经搜索过。 此目录的名称为 SYSTEM。

    • Windows 目录。

    • 在PATH 环境变量中列出的目录。

返回值

如果函数成功,返回值是模块句柄。 如果函数失败,则返回值为 NULL。

备注

它返回可在 GetProcAddress 获取 DLL 函数地址分配的句柄。 AfxLoadLibrary 还用于映射其他可执行模块。

per-process 维护每个外接库模块的引用数。 每次 AfxLoadLibrary 调用,该引用计数递减,每次 AfxFreeLibrary 调用,该引用计数递增。 当引用计数达到零时,模块不从调用进程的地址空间映射,句柄不再有效。

请务必使用 AfxLoadLibraryAfxFreeLibrary (而不是 Win32 函数 LoadLibraryFreeLibrary),如果应用程序使用多个线程,并且动态加载扩展 DLL。 使用 AfxLoadLibraryAfxFreeLibrary 可确保在加载和卸载扩展 DLL 时所执行的启动代码和关闭代码不会损坏全局 MFC 状态。

在应用程序中使用 AfxLoadLibrary 时需要动态链接到 MFC DLL 版本;如果 MFC 作为 DLL 链接到应用程序,AfxLoadLibrary的头文件,Afxdll_.h,仅包括在内。 因为必须链接到 MFC的 DLL 版本以使用或创建扩展 DLL,这是特意设计的。

示例

// The following shows how to create a MDI based application 
// using a generic CView derived class that is implemented in 
// a dynamically loaded MFC Extension DLL. 

typedef CRuntimeClass * (*GETDLLVIEW)();

BOOL CUserApp::InitInstance()
{
   // Standard Application Wizard generated initialization excluded.



...


   // Register the application's document templates.  Document templates 
   //  serve as the connection between documents, frame windows and views 

   //Load MFC Extension DLL based view class.
   m_hViewDll = AfxLoadLibrary(szMyViewDllPath);
   if (!m_hViewDll)
   {
      CString str;
      str.Format(_T("Error: Cannot find component %s"), szMyViewDllPath);
      AfxMessageBox(str);
      return FALSE;
   }

   GETDLLVIEW GetMyView = (GETDLLVIEW)GetProcAddress(m_hViewDll, "GetMyView");
   ASSERT(GetMyView != NULL);

   CMultiDocTemplate* pDocTemplate;
   pDocTemplate = new CMultiDocTemplate(IDR_NVC_MFC_DLLUserTYPE,
      RUNTIME_CLASS(CUserDoc),
      RUNTIME_CLASS(CChildFrame), // custom MDI child frame
      GetMyView());
   if (!pDocTemplate)
      return FALSE;
   AddDocTemplate(pDocTemplate);

   // Standard Application Wizard generated initalization excluded.



...


   return TRUE;
}

int CUserApp::ExitInstance()
{
   if (NULL != m_hViewDll)
   {
      AfxFreeLibrary(m_hViewDll);
      m_hViewDll = NULL;
   }

   return CWinApp::ExitInstance();
}

要求

Header: afxdll_.h

请参见

参考

AfxFreeLibrary

概念

MFC 宏和全局函数