65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 Microsoft Visual C++ 6.0 项目中加载动态链接库 (DLL)

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.81/5 (41投票s)

2004 年 5 月 3 日

2分钟阅读

viewsIcon

570955

本文提供了将 DLL 加载到您的项目中并访问 DLL 提供的服务的指南。

引言

在本文中,我将总结我对将动态链接库 (DLL) 包含到 Microsoft Visual C++ 6.0 项目中,以及使用加载的 DLL 提供的服务的研究结果。

本文的目的是简明扼要地解释您需要做什么才能使用 DLL 中包含的服务(通过服务,我指的是任何函数、类或导出到 DLL 的参数)。 通过执行下面描述的步骤,可以避免我经历的三个星期的“DLL 地狱”。

情况 1:您提供的 DLL 由另一个应用程序提供,并且已借助 OLE (COMM) 生成。

示例: 我需要访问 Rose-RT 的外部接口,该接口由 Rose-RT 的开发人员作为 RrtRes.dll 提供,以便从外部应用程序控制 Rose-RT。

要执行的步骤

  • 在 Microsoft Visual C++ 6.0 中创建一个 MFC 应用程序 (.dll.exe);
  • 转到菜单 View, ClassWizard
  • 选择选项 Add Class…,从类型库中。
  • 浏览到您的 *.dll 所在的位置。
  • 将出现一个窗口,显示您的 *.dll 的内容。 选择您要包含在项目中的所有类(Ctrl+A – 选择所有内容,或 Ctrl + 鼠标点击 – 选择一组特定的类)。
  • 按下按钮 Open。 将生成头文件 *.h*.cpp 实现文件。
  • 关闭 ClassWizard。

现在,您选择在项目中使用的所有服务都可用了!

情况 2:您提供的 DLL 已生成为 MFC 共享 DLL,并且要在单线程代码中使用

示例: 假设您获得了 LoadMe.dll,应该访问其服务,但不能像情况 1 中那样导出。

//You need to declare types to point on classes/functions in LoadMe.dll
//Assume, you have a function in your LoadMe.dll with a name 
//EntryPoint, which takes two parameters of types int and const char *, 
//and is of type void. You need to create a new type as a 
//pointer to that function as it is shown below.

typedef void (*EntryPointfuncPtr)(int argc, const char * argv );  
 
//Declare an HINSTANCE and load the library dynamically. Don’t forget 
//to specify a correct path to the location of LoadMe.dll

HINSTANCE LoadME;
LoadMe = LoadLibrary("..\\enter a Path To Your Dll here\\LoadMe.dll");
 
// Check to see if the library was loaded successfully 
if (LoadMe != 0)
    printf("LoadMe library loaded!\n");
else
    printf("LoadMe library failed to load!\n");

//declare a variable of type pointer to EntryPoint function, a name of 
// which you will later use instead of EntryPoint
EntryPointfuncPtr LibMainEntryPoint;            

// GetProcAddress – is a function, which returns the address of the 
// specified exported dynamic-link library (DLL) function. After 
// performing this step you are allowed to use a variable 
// LibMainEntryPoint as an equivalent of the function exported in 
// LoadMe.dll. In other words, if you need to call 
// EntryPoint(int, const char *) function, you call it as 
// LibMainEntryPoint(int, const char *)

LibMainEntryPoint = (EntryPointfuncPtr)GetProcAddress(LoadMe,"entryPoint");

现在,您可以访问 LoadMe.dll 的任何服务。 祝你好运!

情况 3:您提供的 DLL 已生成为 MFC 共享 DLL,并且要在多线程代码中使用

使用 AfxLoadLibrary() 代替情况 2 中提到的 LoadLibrary()

完成后,不要忘记释放内存并卸载库:FreeLibrary(LoadMe)

© . All rights reserved.