How to call functions by their pointers passing mu

2019-01-29 05:18发布

问题:

I need to make a "function caller" function: it receives a generic function pointer (void *) and a variable number of arguments as arguments and it's got to call this function, passing the arguments, and return a generic pointer to the returning value. However, this entry-function pointer may point to any kind of function (with any returning type), even to functions with a constant number of arguments. It would be something like:

void * function_caller(void * function_pointer, ...) {
  void * returning_value;

  // Call the function and get the returning value

  return returning_value;   // this returning value will be properly casted outside
}

This way, the following code would work:

int function1(int a, char b) {
  // ...
}

void function2(float c) {
  // ...
}

float function3() {
  // ...
}

int main() {
  int v1;
  float v3;

  v1 = *(int *) function_caller((void *) &function1, 10, 'a');  // Which would be equivalent to v1 = function1(10, 'a');
  function_caller((void *) &function2, 3.0);    // Which would be equivalent to function2(3.0);
  v3 = *(float *) function_caller((void *) &function3); // Which would be equivalent to v3 = function3();

  return 0;
}

I know I'll have to use a va_list, but I don't know how to call the function by a pointer passing the arguments.

So, guys, any idea?

回答1:

The bad news is, this is not possible in C, even in unportable C. (GCC has extensions which sound like they do this job, but they do not work in the general case.) It is necessary to write assembly-language shims.

The good news is, other people have already written the shims for you: have a look at libffi. (Manual here. Do not use the "closure" API if you can possibly avoid it.)