本教程详细介绍了在VC++环境下创建动态链接库(DLL)的方法及步骤,并讲解了如何编写代码来调用已存在的DLL。适合初学者快速入门。
在特定情况下调用DLL函数或使用Windows API时需注意以下几点:
1. 使用Win32 API的DLL函数应采用“__stdcall”调用约定。
2. 将C++生成的DLL供标准C语言使用,输出文件需要通过“extern C”进行修饰。如果采用了“__stdcall”的方式,则导出函数名会被修改为C无法识别的形式,因此推荐在.def文件中定义导出项而非直接使用`__declspec(dllexport)`。
下面展示了一个用于创建和调用DLL的示例代码:
SampleDLL.def
```plaintext
LIBRARY sampleDLL
EXPORTS
HelloWorld @1 ; 示例函数名及序号,实际应按需调整。
```
在Microsoft Visual C++ 6.0中可以通过选择“Win32 动态链接库”项目类型或使用MFC向导创建一个新DLL。以下是通过前者方式生成的SampleDLL.cpp示例代码:
```cpp
#include stdafx.h
#define EXPORTING_DLL
#include sampleDLL.h
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
return TRUE;
}
void HelloWorld() {
MessageBox(NULL, TEXT(Hello World), TEXT(In a DLL), MB_OK);
}
```
文件SampleDLL.h
```cpp
#ifndef INDLL_H
#define INDLL_H
#ifdef EXPORTING_DLL
extern __declspec(dllexport) void HelloWorld();
#else
extern __declspec(dllimport) void HelloWorld();
#endif
#endif //INDLL_H
```
下面是一个调用上述示例中的HelloWorld函数的Win32 应用程序项目代码:
SampleApp.cpp
```cpp
#include stdafx.h
#include sampleDLL.h
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
HelloWorld();
return 0;
}
```
需要注意的是,在动态链接时,必须在编译SampleApp项目时连接到由SampleDLL项目生成的库文件(即SampleDLL.lib)。而在运行时加载和调用函数可以使用如下方法:
```cpp
typedef VOID (*DLLPROC)(LPTSTR);
HINSTANCE hinstDLL;
DLLPROC HelloWorld;
hinstDLL = LoadLibrary(sampleDLL.dll);
if (hinstDLL != NULL) {
HelloWorld = (DLLPROC)GetProcAddress(hinstDLL, HelloWorld);
if (HelloWorld != NULL)
HelloWorld();
}
FreeLibrary(hinstDLL);
```
以上步骤和代码示例展示了如何创建一个简单的C++ DLL,并从另一个程序中调用其中的函数。