如何解决如何将此代码封装为 C++ 中的函数?
HINSTANCE hDll = LoadLibrary(_T("Test1.dll"));
if (NULL != hDll)
{
typedef CTest1Dlg*(*pDllFun)(int val);
pDllFun pDlg = (pDllFun)GetProcAddress(hDll,"ShowDlg");
if (NULL != pDlg)
{
pDlg(val);
}
}
主要是:typedef CTest1Dlg*(*pDllFun)(int val);
这行代码唯一的区别就是CTest1Dlg
不同,会变成CTest2Dlg
或者other,但是它们的参数是一样的
解决方法
这适合函数模板。
最直接的参数化可能是
template<typename Dlg>
void testDllFunction(LPCTSTR dll,const char* name,int val)
{
HINSTANCE hDll = LoadLibrary(dll);
if (hDll != NULL)
{
typedef Dlg*(*pDllFun)(int);
pDllFun pDlg = reinterpret_cast<pDllFun>(GetProcAddress(hDll,name));
if (pDlg != NULL)
{
pDlg(val);
}
}
}
// ...
testDllFunction<CTest1Dlg>(_T("Test1.dll"),"ShowDlg"));
但是将函数的加载和调用分开可能是个好主意。
这里有一个建议:
template<typename Dlg>
using DlgFunction = Dlg*(*)();
template<typename Dlg>
bool loadFunction(LPCTSTR dll,DlgFunction<Dlg>& fun)
{
HINSTANCE hDll = LoadLibrary(dll);
if (!hDll)
return false;
fun = reinterpret_cast<DlgFunction<Dlg>>(GetProcAddress(hDll,name));
return fun != NULL
}
// ...
DlgFunction<CTest1Dlg> test1;
if (loadFunction(_T("Test1.dll"),"ShowDlg",test1))
test1(12);
DlgFunction<CTest2Dlg> test2;
if (loadFunction(_T("Test2.dll"),"Kittens",test2))
test2(34);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。