如何调用其指针的函数传递多个参数用C? [英] How to call functions by their pointers passing multiple arguments in C?

查看:364
本文介绍了如何调用其指针的函数传递多个参数用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一个函数调用功能:它接收一个泛型函数指针(无效* )和参数作为参数变量数,它有来电这个函数,传递的参数,以及通用指针返回返回值。但是,此入口函数指针可以指向任何类型的功能(带任何返回类型),即使以恒定数目的参数函数。这将是这样的:

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
}

这样,下面的code将工作:

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;
}

我知道我将不得不使用一个的va_list ,但我不知道如何通过传递参数的指针调用该函数。

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?

推荐答案

坏消息是,这是不可能的C,即使在不可移植C.(GCC具有的扩展声如的他们做这份工作,但他们并不在一般情况下正常工作。)它是必要写汇编语言垫片。

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.

可喜的是,其他人已经写了你的垫片:看看 libffi 。 (手册这里。不要使用在封闭的API,如果你都不可能避免。)

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.)

这篇关于如何调用其指针的函数传递多个参数用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆