卸载动态库
BOOL FreeLibrary( HMODULE hModule //DLL的实例句柄 ); #include <iostream> #include <Windows.h> using namespace std; typedef int(*FUNC)(int m,int n); int main(){ HINSTANCE hDll = LoadLibrary("CPPDll.dll"); cout << "hDll:" << hDll << endl; FUNC add = (FUNC)GetProcAddress(hDll,"CPPdll_add"); cout << "addAdress:" << add << endl; int sum = add(5,4); cout << "sum:" << sum << endl; FUNC sub = (FUNC)GetProcAddress(hDll,"CPPdll_sub"); cout << "subAdress:" << sub << endl; int su = sub(5,4); cout << "sub:" << su << endl; FUNC mul = (FUNC)GetProcAddress(hDll,"CPPdll_mul"); cout << "mulAdress:" << mul << endl; int mu = mul(5,4); cout << "mul:" << mu << endl; system("pause"); FreeLibrary(hDll); return 0; } 2.4动态库中封装类
在类名称前增加_declspec(dllexport)定义,例如:
class _declspec(dllexport) CMath{ ... };
通常使用预编译开关切换类的导入导出定义,例如:
#ifdef DLLCLASS_EXPORTS #define EXT_CLASS _declspec(dllexport) //dll #else #definE EXT_CLASS _declspec(dllimport) //使用者 #endif class EXT_CLASS CMath{ ... };例子:
头文件
#ifndef _ClASSDLL_H #define _CLASSDLL_H #ifdef DLLCLASS_EXPORTS #define EXT_CLASS _declspec(dllexport) //dll #else #define EXT_CLASS _declspec(dllimport) //使用者 #endif class EXT_CLASS CMath{ public: int add(int m,int n); int sub(int m, int n); }; #endif源文件
#define DLLCLASS_EXPORTS #include "ClassDll.h" int CMath::add(int m,int n){ return m + n; } int CMath::sub(int m,int n){ return m - n; }调用动态库中的封装类
#include "..\ClassDll\ClassDll.h" #include <iostream> using namespace std; #pragma comment(lib,"../Debug/ClassDll.lib") int main(){ CMath myMath; int sum = myMath.add(5,4); int sub = myMath.sub(5,4); cout << "sum=" << sum << ",sub=" << sub << endl; system("pause"); return 0; }