动态链接库在C++中非常重要,写了一个简单的例子用于DLL的导出和调用。
DLL的生成
头文件
#include<iostream>
#include<stdexcept>
using namespace std;
#define TESTAPI __declspec(dllexport)
// 函数定义
extern "C" {
TESTAPI int add(int a, int b);
TESTAPI int sub(int a, int b);
TESTAPI int mul(int a, int b);
TESTAPI int div_(int a, int b);
}
源文件
#include"test.h"
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div_(int a, int b) {
try {
if (b == 0) {
throw std::runtime_error("Division by zero error!"); // 抛出异常
}
return a / b;
}
catch (const std::runtime_error& e) {
cout << "Error: " << e.what() << endl; // 捕获并处理异常
return 0; // 或根据需求返回其他值
}
}
配置类型DLL
生成DLL
‘
DLL的调用
把生成的test1.dll放在测试工程test_useDll的目录下
调用DLL中的接口
#include <iostream>
#include <windows.h>
using namespace std;
// 声明函数指针
typedef int(*AddFunc)(int, int);
typedef int(*SubFunc)(int, int);
typedef int(*MulFunc)(int, int);
typedef int(*DivFunc)(int, int);
int main() {
// 加载DLL
HINSTANCE hDLL = LoadLibraryA("test1.dll");
if (!hDLL) {
cout << "Failed to load DLL." << endl;
return 1;
}
// 获取函数地址
AddFunc add = (AddFunc)GetProcAddress(hDLL, "add");
SubFunc sub = (SubFunc)GetProcAddress(hDLL, "sub");
MulFunc mul = (MulFunc)GetProcAddress(hDLL, "mul");
DivFunc div_ = (DivFunc)GetProcAddress(hDLL, "div_");
if (!add || !sub || !mul || !div_) {
cout << "Failed to get function address." << endl;
FreeLibrary(hDLL);
return 1;
}
// 调用DLL中的函数
int a = 10, b = 5;
cout << "add(a, b) = " << add(a, b) << endl;
cout << "sub(a, b) = " << sub(a, b) << endl;
cout << "mul(a, b) = " << mul(a, b) << endl;
cout << "div_(a, b) = " << div_(a, b) << endl;
// 释放DLL
FreeLibrary(hDLL);
return 0;
}