DLL中对象的构造与析构

动态链接库中全局变量的构造与析构:

背景:你在当前main函数中通过LoadLibrary来加载MFCLibraryDll.dll

1 MFCLibraryDll中的全局变量A b的创建与析构会自动执行:

1)LoadLibrary执行时第一时间创建LoadLibrary中的全局变量;

2)main函数退出的时候自动卸载LoadLibrary加载的DLL,并执行MFCLibraryDll中全局变量的析构函数;

3)DLL中的静态变量的生命期类似于全局变量,也会被自动管理;

main函数:

#include "stdafx.h"
#include 
#include 
#include 
#include 
using namespace std;

int main()
{
	std::cout << "Hello CallMFCLibrary!" << endl;
	string str = "MFCLibraryDll.dll";
	HMODULE libraryHandle = ::LoadLibrary(str.c_str());

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

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

    return 0;
}

MFCLibraryDll.dll

#include 
using namespace std;

class A
{
public:
	A()
	{
		std::cout << "MFCLibraryDll A::A()" << endl;
	}
	~A()
	{
		std::cout << "MFCLibraryDll A::~A()" << endl;
	}
	static A s_a;
};

A A::s_a;//静态变量

A b;//全局变量

extern "C" void PASCAL EXPORT ExportedFunction()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	A a;//局部变量

	// 此处为普通函数体
	std::cout << "MFCLibraryDll void PASCAL EXPORT ExportedFunction()" << endl;
}

输出:

DLL中对象的构造与析构_第1张图片

你可能感兴趣的:(DLL,Visual,C++,2010)