#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);
显示加载DLL封装
最新推荐文章于 2023-09-24 23:56:32 发布