创建及使用Windows DLL(Windows 核心编程 第5版)

创建步骤

  1. 创建头文件
/*************************************************************************
Module: MyLib.h
*************************************************************************/
#ifdef MYLIBAPI
// MYLIBAPI should be defined in all of the DLL's source code modules before this header file is included.
// All functions/variables are being exported
#else
// This header file is included by an EXE source code module
// Indicate that all functions/variables are being imported
#define MYLIBAPI extern "C" _declspec(dllimport)
#endif

//Define any data structures and symbols here

//Define exported variables here .(NOTE: Avoid exporting variables.)
MYLIBAPI int g_nResult;

//Define exported function prototypes here.
MYLIBAPI int Add(int nLeft , int nRight);
// End of File /
  1. 创建包含该头文件的源文件
/*****************************************************************
Module: MyLibFile1.cpp
******************************************************************/
// Include the standar Windows and C-Runtime header files here.
#include <windows.h>

//This DLL source code file exports functions and variables
#define MYLIBAPI extern "C" _declspce(dllexport)

//Include the exported data structures,symbols,functions,and variable.
#include "MyLib.h"

// Place the code for this DLL source code file here
//这里不需要MYLIBAPI标识符的原因是编译器在解析头文件的时候会记住应该导出那些变量或函数
int g_nResult;

int Add(int nLeft,int nRight) {
    g_nResult = nLeft + nRight;
    return(g_nResult)
}

//End of File

搜索DLL顺序

  1. 包含可执行文件的目录
  2. Windows的系统目录,该目录可以通过GetSystemDirectory得到
  3. 16位的系统目录,即Windows目录中的System子目录
  4. Windows目录,该目录可以通过GetWindowsDirectory得到
  5. 进程的当前目录
  6. PATH环境变量中所列出的目录

调用

  1. 显示载入:HMODULE LoadLibray(PCTSTR pszDLLPathName)
  2. 显示卸载:BOOL FreeLibray(HMODULE hInstDll)
posted @ 2022-04-27 21:07  源世  阅读(221)  评论(0)    收藏  举报