Assuming I have the runtime memory address of a function in an Application and I know the return type of said function, is it possible to call the function, knowing the functions return type, its arguments and calling convention, using a variadic template?
The templated function has to support both void and non-void return types. Due to the fact that we are dealing with function pointers, the compiler shouldn't complain, despite return ptr.
I thought about doing something like this:
template<typename ReturnType, typename Address, typename... Args>
ReturnType function_caller(Address address, Args... args)
{
ReturnType(*ptr)(Args...) = address;
return ptr(args...);
}
int main()
{
auto address = 0x100;
auto address2 = 0x200;
function_caller<void>(&address, 1, 1); // Function with return type void.
int result = function_caller<int>(&address2, 1, 2, 3.f, "hello");
// result should contain the int value we received by calling the function at 0x200
}
Sadly the compiler throws the error C2440: It can't convert the Address "address" to 'ReturnType (__cdecl *)(int,int)'
I would really appreciate your help with this problem. I know i could just split this wrapper into 2 functions: one for void calls and one for non-void calls, but i hope there is a more elegant, template-supported solution.
Thank you and have a nice day!