【環境:VS2019】
【編寫一個DLL並導出函數】
1、新建動態鏈接庫:V_BJZ
[framework.h]
#pragma once #define WIN32_LEAN_AND_MEAN // 從 Windows 頭文件中排除極少使用的內容 // Windows 頭文件 #include <windows.h> extern "C" _declspec(dllexport) int ReturnSum(int a, int b); //導出聲明,_declspec(dllexport)是關鍵字
[dll1.cpp]
#include "framework.h" #include "pch.h" int ReturnSum(int a, int b) //該DLL需要導出的函數功能:加法 { return a + b; }
2、編譯鏈接后的文件夾(划重點:之后要用的呀~)
【使用動態加載方式調用該函數】
1、新建項目V_DY
[DY.cpp]
#include<iostream> #include<wtypes.h> using namespace std; typedef int(*pReturnSum)(int a, int b); //函數指針聲明 int main() { HINSTANCE hDLL; pReturnSum ReturnSum; hDLL = LoadLibrary("G:\\Cplus_workspace\\V_1\\V_BJZ\\Debug\\V_BJZ.dll"); //加載 DLL文件 if (hDLL == NULL) { cout << "Error!!!\n"; } ReturnSum=(pReturnSum)GetProcAddress(hDLL,"ReturnSum"); //取DLL中的函數地址,以備調用 int a, b, sum; cin >> a >> b; sum = ReturnSum(a, b); cout<<"sum = "<<sum<<endl; FreeLibrary(hDLL); return 0; }
【使用靜態加載的方式調用該函數】
1、新建項目V_DY2
2、將V_BJZ項目中的framework.h文件和V_BJZ.lib,V_BJZ.dll置於V_DY2項目文件夾下
[DY2.cpp]
#include<iostream> #include<wtypes.h> #include "framework.h" //引用V_BJZ項目中的頭文件 #pragma comment(lib,"G:\\Cplus_workspace\\V_1\\V_DY2\\V_BJZ.lib") //將V_BJZ.lib庫文件連接到目標文件中(即本工程) using namespace std; int main() { int a, b, sum; cin >> a >> b; sum=ReturnSum(a, b); cout<<"sum = "<<sum<<endl; return 0; }
【效果圖】
【遇到的問題】
1、程序中使用的文件路徑建議使用雙斜杠。單斜杠會提示語法錯
2、靜態加載方式不僅要把文件放到項目文件夾下,還要在VS上導入一下(VS2019快捷鍵為Shift Alt A),否則提示語法錯
3、靜態加載方式EXE單獨執行時需將調用的DLL文件放在同目錄下,否則報錯
4、頭文件不需要的不建議寫,會報出稀奇古怪的錯誤
5、靜態加載方式將導入聲明寫上了反而報錯,去掉就沒問題了