C++中调用DLL中的函数的两种方式

C++中调用DLL中的函数的两种方式

一、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

#include

#include

#include

#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;

}

🌟 相关推荐

淘宝直播新手需要什么条件?怎么操作?淘宝直播新手完全指南:开通条件与操作步骤详解
Linux查看安装的软件
beat365最新版2022

Linux查看安装的软件

📅 07-04 👁️ 156
为什么任何非零数的零次方(零次幂)都为1?
beat365最新版2022

为什么任何非零数的零次方(零次幂)都为1?

📅 07-03 👁️ 9493