首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

非 MFC 環境下 DLL 開發入門:從建立到隱式/顯式載入全解析

     編輯:關於VC++

前言

本文以 Visual C++ 2003 為環境,以最簡潔的 Win32 主控台專案示範非 MFC DLL 的完整生命週期:建立、匯出函數、產生導入庫、以及兩種載入方式的實戰代碼。適合初學者快速掌握 DLL 核心機制。

專案建立與標頭檔設計

選擇「Win32 主控台應用程式」→ 進階頁籤勾選「DLL」與「空白專案」。核心標頭檔 DLLTutorial.h 關鍵點:

  • 使用 #ifndef/_DEFINE 防重複包含
  • extern "C" 防止 C++ 名稱修飾,確保 C/C++ 互通
  • 透過 DLL_EXPORT 巨集切換 __declspec(dllexport) / dllimport
#ifndef _DLL_TUTORIAL_H_
#define _DLL_TUTORIAL_H_
#include <iostream>
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
extern "C" {
    DECLDIR int Add(int a, int b);
    DECLDIR void Function(void);
}
#endif

匯出函數實作

在 DLLTutorial.cpp 定義 DLL_EXPORT 後實作函數:

#include <iostream>
#include "DLL_Tutorial.h"
#define DLL_EXPORT
extern "C" {
    DECLDIR int Add(int a, int b) { return a + b; }
    DECLDIR void Function(void) { std::cout << "DLL Called!" << std::endl; }
}

模組定義檔 替代方案

建立 .def 檔同樣可匯出函數,非 Microsoft 專屬,攜帶性較佳:

LIBRARY dll_tutorial
DESCRIPTION "our simple DLL"
EXPORTS
    Add @1
    Function @2

編譯同時產生 .dll 與 .lib(導入庫),後者供隱式連結使用。

隱式連結:最簡單的使用方式

  1. 將 .h、.lib、.dll 複製至呼叫端專案目錄
  2. 專案屬性 → 連結器 → 輸入 → 附加相依性加入 DLLTutorial.lib,或用 #pragma comment(lib, "DLLTutorial.lib")
  3. 直接 #include "DLLTutorial.h" 呼叫函數,無須額外代碼

顯式連結:無需標頭與導入庫的動態載入

適用於外掛架構、選用性功能模組:

#include <iostream>
#include <windows.h>
typedef int (*AddFunc)(int, int);
typedef void (*FunctionFunc)();

int main() {
    AddFunc _AddFunc = nullptr;
    FunctionFunc _FunctionFunc = nullptr;
    HINSTANCE hInst = LoadLibrary("DLL_Tutorial.dll");
    if (!hInst) return 1;

    _AddFunc = (AddFunc)GetProcAddress(hInst, "Add");
    _FunctionFunc = (FunctionFunc)GetProcAddress(hInst, "Function");
    if (!_AddFunc || !_FunctionFunc) { FreeLibrary(hInst); return 1; }

    std::cout << _AddFunc(23, 43) << std::endl;
    _FunctionFunc();
    std::cin.get();
    FreeLibrary(hInst);
    return 0;
}

關鍵步驟:LoadLibrary 取得模組句柄 → GetProcAddress 取得函數位址 → 函數指標轉型呼叫 → FreeLibrary 釋放。

總結

掌握 __declspec 與 .def 兩種匯出方式、隱式/顯式連結的適用場景,即具備 DLL 開發基礎。進階主題包含 DLL 生命週期管理 (DllMain)、執行緒區域儲存 (TLS)、跨模組記憶體管理、版本相容性等,留待後續探索。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved