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

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值