HelloWorld示例 DLL 和应用程序XXXXXXXX 在 Microsoft
Visual C++
6.0 中,可以通过选择“Win32 动态链接库”
项目类型
或“MFC 应用程序向导 (dll)”来创建 DLL。下面的代码是一个在 Visual C++ 中通过使用“Win32 动态链接库”项目类型创建的 DLL 的示例。
// SampleDLL.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);
}
/ File: SampleDLL.h //#ifndef INDLL_H #define INDLL_H #ifdef EXPORTING_DLLextern __declspec(dllexport) void HelloWorld() ; #elseextern __declspec(dllimport) void HelloWorld() ; #endif #endif
下面的代码是一个“Win32 应用程序”项目的示例,该示例调用 SampleDLL DLL 中的导出 DLL 函数。 / SampleApp.cpp //#include "stdafx.h" #include "sampleDLL.h" int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { HelloWorld(); return 0; }
注意:在加载时动态链接中,您必须链接在生成 SampleDLL 项目时创建的 SampleDLL.lib
导入库
。
在运行时动态链接中,您应使用与以下代码类似的代码来调用 SampleDLL.dll 导出 DLL 函数。
...
typedef VOID (*DLLPROC) (LPTSTR);
...
HINSTANCE hinstDLL;
DLLPROC HelloWorld;
BOOL fFreeDLL;
hinstDLL = LoadLibrary("sampleDLL.dll");
if (hinstDLL != NULL)
{
HelloWorld = (DLLPROC) GetProcAddress(hinstDLL, "HelloWorld");
if (HelloWorld != NULL)
(HelloWorld);
fFreeDLL = FreeLibrary(hinstDLL);
}
...