2

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
austere
  • 157
  • 7

1 Answers1

4

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.

  • 1
    worked Perfectly (with a typename in front of signature), thanks very much! It does bring up one addition question though... I wonder how I can adapt this solution to VC++ 11 takes care of its various function calling conventions. If I were to insert a __cdecl or __stdcall in between the reinterpret cast, the compiler won't like it (returns syntax error). That's because these calling declarations can't be behind but in front of the return type.... Somehow we have to dissect the signature to insert it in the middle. Perhaps a problem to solve after variadic templates are implemented. – austere Nov 27 '12 at 11:55