一、DLL源文件:
extern "C" __declspec(dllexport)
int add(int a, int b)
{
return a + b;
}
二、静态调用:
#pragma comment(lib, "DemoDLL.lib")
extern "C" int add(int a, int b);
using namespace std;
// 静态调用DLL库
int static_call(int a, int b)
{
return add(a, b);
}
三、动态调用:
// 动态调用DLL库
int dynamic_call(int a, int b)
{
typedef int(*AddFunc)(int, int);
HMODULE module = LoadLibrary(L"DemoDLL.dll");
if (module == NULL)
{
cout << "加载DemoDLL.dll动态库失败" << endl;
return -1;
}
AddFunc add = (AddFunc)GetProcAddress(module, "add");
return add(a, b);
}
四、完整调用代码:
#include <sstream>
#include <iomanip>
#include <iostream>
#include <Windows.h>
#pragma comment(lib, "DemoDLL.lib")
extern "C" int add(int a, int b);
using namespace std;
// 静态调用DLL库
int static_call(int a, int b)
{
return add(a, b);
}
// 动态调用DLL库
int dynamic_call(int a, int b)
{
typedef int(*AddFunc)(int, int);
HMODULE module = LoadLibrary(L"DemoDLL.dll");
if (module == NULL)
{
cout << "加载DemoDLL.dll动态库失败" << endl;
return -1;
}
AddFunc add = (AddFunc)GetProcAddress(module, "add");
return add(a, b);
}
int main()
{
int n = 100, m = 200;
cout << static_call(m, n) << endl;
cout << dynamic_call(m, n) << endl;
return 0;
}