How can I call (not define) a function with a variable number of arguments in C?

前端 未结 6 1754
感情败类
感情败类 2021-01-20 01:05

Is there any way to make this code shorter?

long call_f(int argc, long *argv) {
  switch (argc) {
    case 0:
      return f();
      break;
    case 1:
             


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-20 01:13

    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:

    1. 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.
    2. 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

提交回复
热议问题