本文將整理動態鏈接庫dll的封裝方法及調用的方法。(以VS2010為開發平台)
1,動態鏈接庫dll的封裝方法
封裝步驟:
(1),在VS2010中新建一個win32->dll工程;
(2),新建一個頭文件Dll1.h

#ifndef DLL1_API #define DLL1_API extern "C" _declspec (dllimport) #endif DLL1_API int add(int a , int b); DLL1_API int substract(int a ,int b);
(3),新建一個cpp文件Dll1.cpp

// Dll1.cpp : 定義 DLL 應用程序的導出函數。 // #include "stdafx.h" #define DLL1_API extern "C" _declspec(dllexport) #include "Dll1.h" int add(int a , int b) { return a+b; } int substract(int a , int b) { return a-b; }
編譯生成
在debug文件夾中會生成相應的DLL及LIB文件:*.dll *.lib
2,動態鏈接庫dll的調用方法
新建一個win32的控制台應用程序dlltest
(1)調用方法一:
a,拷貝dll的封裝編譯生成的*dll,*.lib,Dll1.h文件到dlltest工程目錄下;
b,在cpp文件中添加如下的代碼:

// dlltest2.cpp : 定義控制台應用程序的入口點。 // #include "stdafx.h" #include<iostream> #include <Windows.h> #include "Dll1.h" #pragma comment (lib,"Dll1.lib") using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int a = 10; int b =2; cout<<add(a,b)<<endl;; cout<<substract(a,b); system("pause"); return 0; }
(2)調用方法二:
備注: 方法二和方法一相比 , 不用添加*.h頭文件 和代碼#pragma comment (lib,"Dll1.lib")

// dlltest2.cpp : 定義控制台應用程序的入口點。 // #include "stdafx.h" #include<iostream> #include <Windows.h> //#include "Dll1.h" //#pragma comment (lib,"Dll1.lib") using namespace std; typedef int (*func)(int, int); int _tmain(int argc, _TCHAR* argv[]) { HMODULE h = LoadLibraryA("Dll1.dll"); func f = (func)GetProcAddress(h, "substract"); cout<<f(10,2); /*int a = 10; int b =2; cout<<add(a,b)<<endl;; cout<<substract(a,b);*/ system("pause"); return 0; }
這種方法中
HMODULE h = LoadLibraryA("Dll1.dll"); func f = (func)GetProcAddress(h, "substract");
必須在生成dll文件時 extern "C";