显示加载DLL封装

#ifndef DYNALINK_H_
#define DYNALINK_H_

#include <windows.h>
#include <string>

class DynaLink
{
public:
	DynaLink() 
		: hDll_(NULL)
	{
	}

	DynaLink(const std::wstring &name)
		: hDll_(NULL)
	{
		open(name); 
	}

	virtual ~DynaLink() = 0
	{
		close();
	}

	bool open(const std::wstring &name)
	{
		hDll_ = LoadLibrary(name.c_str());
		return (hDll_?true:false);
	}

	void close()
	{
		if (hDll_)
		{
			FreeLibrary(hDll_);
			hDll_ = NULL;
		}
	}

	bool isLoaded() const
	{
		return (hDll_ != NULL); 
	}

	std::wstring name(bool full = false) const
	{
		if (!isLoaded()) { return L""; }

		wchar_t path[MAX_PATH] = {0};
		GetModuleFileName(hDll_, path, MAX_PATH-1);
		std::wstring ret = path;
		if (!full)
		{
			int pos = ret.find_last_of(L'\\');
			ret = ret.substr(pos+1, ret.size()-pos-1);
		}
		return ret;
	}

	typedef void (*Function)();
	bool getFunction(const std::string &funcName, Function &func)
	{
		if (!isLoaded()) { return false; }

		func = (Function)GetProcAddress(hDll_, funcName.c_str());
		return (func?true:false);
	}

private:
	HMODULE hDll_;
};

#endif // DYNALINK_H_

// 使用示例
class ServerDll : public DynaLink
{
public:
	ServerDll() : DynaLink(L"D:\\my.dll")
	{
		if (!getFunction("InitConnection", (Function&)MyInit))
		{
			close();
		}
		else
		{
			std::wcout << "fullname:" << name(true) << std::endl;
			std::wcout << "name:" << name() << std::endl;
		}
	}

	unsigned short (WINAPI *MyInit)(void*);
	// ...
};

ServerDll link;
link.MyInit(NULL);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值