Function pointer to multiple argument C++11 std::function: Templating GetProcAddress

為{幸葍}努か 提交于 2020-01-15 05:03:27

问题


I am trying to return a function instance from a FARPROC address given by another function that calls GetProcAddress. Came up with an interesting issue. Here's the function:

template<class FT>
std::function<FT> to_function(FARPROC address) {
    return address;
}

Later on I would create a no input function without any issues:

auto try1 = to_function<int()>(addr1);

However when the function takes an input, the visual c++ 11 compiler explodes:

auto try2 = to_function<int(int)>(addr2);

It rightfully returns:

Error C2197: 'int (__stdcall *)(void)' : too many arguments for call

The type in question is equivalent to FARPROC which is what is returned by GetProcAddress regardless of the argument list of the function.

My question, to get to the point, is how would I get around this issue by casting FARPROC to an appropriate type for std::function given the simple function prototype of to_function? Cheers in advance.


回答1:


I would suggest you first cast your pointer, and then wrap it into a std::function:

template<Signature>
std::function<Signature> to_function(FARPROC f)
{
    return std::function<Signature>(reinterpret_cast<Signature*>(f));
}

IMHO it would be a good idea to name such a function cast_to_function. Its name should sound dangerous.



来源:https://stackoverflow.com/questions/13558875/function-pointer-to-multiple-argument-c11-stdfunction-templating-getprocadd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!