如何将参数绑定到C函数指针?

时间:2013-10-10 19:51:38

标签: c function pointers arguments bind

我已经做了一些关于如何在C中使用函数指针的研究,我试图做一些面向对象的事情模型。因此,为了模拟这样的事情,我被告知我必须添加结构的函数指针,这样它们就会成为一个对象'。

由于我在C语言编程方面相当新,这个问题可能看起来有点愚蠢(或者很容易回答),但在互联网上,我刚刚找到了关于C ++的例子,而这不是我要搜索的内容

以下是我想展示的示例,以便您可以轻松了解我的问题:

try.h-文件:

struct thing {
  void (*a)(int, int);
};
void add(int x, int y);

try.c-文件:

#include <stdio.h>
#include <stdlib.h>
#include "try.h"

void add(int x, int y) {
  printf("x + y = %d\n", x+y);
}

int main(int argc, char* argv[]) {
  struct thing *p = (struct thing*) malloc(sizeof(struct thing));
  p->a = &add;
  (*p->a)(2, 3);
  free(p);
  p = NULL;
  return 0;
}

作为示例,我希望始终x = 2,因此struct thing中的函数指针将是这种指针:void (*a)(int)而不是void (*a)(int, int)。< / p>

如何在将函数指针传递给struct(行x = 2)时绑定参数p->a = &add;?这在C中甚至可能吗?在C ++中,我看到过类似std::bind的内容,但我无法在C中执行此操作。

4 个答案:

答案 0 :(得分:2)

函数指针必须与它指向的函数具有相同的签名(类型和参数),所以你不能真的这样做。

你可以用另外几个函数包装bind和call:

struct thing {
  void (*a)(int, int);
  int x;
};
...
void bind1st( struct thing *p, int arg )
{
  p->x = arg;
}

void call( struct thing *p, int arg )
{
  p->a( p->x, arg );
}

你会想要尝试一下,但这应该让你开始。

答案 1 :(得分:0)

我也遇到过类似的问题,并且我使用以下方法解决了问题,使用gcc对其进行了编译,使用clang对其进行了编译,

#include <stdio.h>

typedef int (*add_t) (int);

add_t add2(int x) {
  int add1(int y) {
    return x + y; 
  }
  return add1;
}

int main() {

  //add2(2);
  printf("%d\n", add2(2)(3));
}

答案 2 :(得分:0)

我认为这是最好的解决方案。


typedef void(*call_type)();
call_type bind(void (*f)(int,int), int a, int b) {
    void call()  {
        f(a,b);
    }

    return &call;
}

void f(int a, int b){
    printf("%d, %d", a, b);
}

int main(){
    call_type c = bind(f, 5, 4);

    c();
}


答案 3 :(得分:0)

一种还没有人讨论过的方法是使用一些 JIT 逻辑(我现在不会提供一个工作示例,因为我还没有尝试过,但我会在某个时间将它用于 RPC图书馆)。严格来说,这并不是 C 语言的特性,它只适用于可以写入可执行内存段的 CPU/MCU 架构(在 x86_64、x86、某些 ARM 等上是可能的)。

原理其实只是动态构造一个函数,它会以类似于python定义动态嵌套函数的方式调用包装函数。

你可以使用的一些库:libgccjit、libjit、gnu-ligthning、llvm 等

相关问题