EXE多次LoadLibrary会怎么样

DLL 文章列表

多次LoadLibrary,只有第一次会真正加载,后面一直驻留在EXE内存中。

只要不调用FreeLibrary,DLL一直都在。

后面的LoadLibrary等同于空操作。

具体原理参考:进程EXE、DLL加载到内存中的过程 https://blog.csdn.net/calmreason/article/details/84404293

CllDLL.cpp

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>
#include <functional>
using namespace std;

void f()
{
	string str = "Win32DLL.dll";
	HMODULE libraryHandle = ::LoadLibrary(str.c_str());

	if (libraryHandle != NULL)
	{
		typedef int (WINAPI* EXECUTOR_FUNC)(void);
		typedef function<void(void)> Handler;

		EXECUTOR_FUNC function = (EXECUTOR_FUNC)GetProcAddress(libraryHandle, "fnWin32DLL");
		if (function)
		{
			cout << function() << endl;
		}
		else
		{
			cout << "can not find function " << endl;
		}
	}
	else
	{
		cout << "can not loadlibrary!" << endl;
	}
}

int main()
{
	f();
	f();
    return 0;
}

DLL.cpp

// Win32DLL.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "Win32DLL.h"

#include <iostream>
#include <string>
using namespace std;

// 这是导出变量的一个示例
WIN32DLL_API int nWin32DLL=0;


class A
{
public:
	A(const string& id = ""):m_id(id) { cout << "A("<<m_id<<")" << endl; }
	~A() { cout << "~A(" << m_id << ")" << endl; }
private:
	string m_id;
};

A a("a in global");

// 这是导出函数的一个示例。
WIN32DLL_API int fnWin32DLL(void)
{
	A a("a in fnWin32DLL");
    return 42;
}

// 这是已导出类的构造函数。
// 有关类定义的信息,请参阅 Win32DLL.h
CWin32DLL::CWin32DLL()
{
    return;
}

输出:

A(a in global)
A(a in fnWin32DLL)
~A(a in fnWin32DLL)
42
A(a in fnWin32DLL)
~A(a in fnWin32DLL)
42
~A(a in global)
请按任意键继续. . .

 

可以看出两次LoadLibrary只创建了一个global对象,并在EXE退出的时候释放了这个global对象。

另参考:DLL中对象的构造与析构 https://blog.csdn.net/calmreason/article/details/83957799

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值