网站优化的论文,上海最大企业前十名,网站后台管理规定,公司网站网页动态链接库在C中非常重要#xff0c;写了一个简单的例子用于DLL的导出和调用。
DLL的生成
头文件
#includeiostream
#includestdexcept
using namespace std;#define TESTAPI __declspec(dllexport)// 函数定义
extern C {TESTAPI int add(in…动态链接库在C中非常重要写了一个简单的例子用于DLL的导出和调用。
DLL的生成
头文件
#includeiostream
#includestdexcept
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);
}源文件
#includetest.hint 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() {// 加载DLLHINSTANCE 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;// 释放DLLFreeLibrary(hDLL);return 0;
}结果