There's actually a method to call a function at run-time if you know its calling convention and which parameters it receives. This however lies out of the standard C/C++ language scope.
For x86 assembler:
Assuming the following:
- You know to prepare all the parameters for your function in a solid buffer, exactly in the manner they'd be packed on the stack.
- Your function doesn't take/return C++ objects by value.
You may use then the following function:
int CallAnyFunc(PVOID pfn, PVOID pParams, size_t nSizeParams)
{
// Reserve the space on the stack
// This is equivalent (in some sense) to 'push' all the parameters into the stack.
// NOTE: Don't just subtract the stack pointer, better to call _alloca, because it also takes
// care of ensuring all the consumed memory pages are accessible
_alloca(nSizeParams);
// Obtain the stack top pointer
char* pStack;
_asm {
mov pStack, esp
};
// Copy all the parameters into the stack
// NOTE: Don't use the memcpy function. Because the call to it
// will overwrite the stack (which we're currently building)
for (size_t i = 0; i < nSizeParams; i++)
pStack[i] = ((char*) pParams)[i];
// Call your function
int retVal;
_asm {
call pfn
// Most of the calling conventions return the value of the function (if anything is returned)
// in EAX register
mov retVal, eax
};
return retVal;
}
You may need to adjust this function, depending on the calling convention used