通过模板类对象操作调用函数

分析Redis源码时,在封装WINDOWS API调用时,通过模板类对象的操作符调用函数。该模板可以作为Windows API 直接导入调用模板

#include <Windows.h>
#include <string>
#include <map>
using namespace std;


class DLLMap : map<string, HMODULE> {
public:
static DLLMap& getInstance();


private:
DLLMap();
DLLMap(DLLMap const&);  // Don't implement to guarantee singleton semantics
void operator=(DLLMap const&); // Don't implement to guarantee singleton semantics


public:
LPVOID getProcAddress(string dll, string functionName);
virtual ~DLLMap();
};

template <typename R, typename... T>
class dllfunctor_stdcall {
public:
dllfunctor_stdcall(string dll, string function)
{
_f = (R(__stdcall *)(T...))DLLMap::getInstance().getProcAddress(dll, function.c_str());
}
R operator()(T... args) { return _f(args...); }


private:
R(__stdcall *_f)(T...);
};

用法:

auto f_accept = dllfunctor_stdcall<SOCKET, SOCKET, struct sockaddr*, int*>("ws2_32.dll", "accept");

调用时:  f_accept(S1, S2, addr, &ret);

   



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页