如何将此代码封装为 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);