5

我已经对如何在 C 中使用函数指针进行了一些研究,并且我正在尝试做一些面向对象的模型。因此,要对这样的事情进行建模,我被告知我必须将函数指针添加到结构中,以便它们成为一种“对象”。

由于我对 C 编程很陌生,这个问题可能看起来有点愚蠢(或者很容易回答),但是在 Internet 上,我只是找到了有关 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;
}

作为一个例子,我想要 always x = 2,所以函数指针struct thing将是这种指针:void (*a)(int)并且void (*a)(int, int)不再是。

x = 2将函数指针传递给结构(行)时如何绑定参数p->a = &add;?这在C语言中甚至可能吗?在 C++ 中我见过类似的东西std::bind,但我无法在 C 中做到这一点。

4

4 回答 4

3

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

您可以将绑定和调用包装在另外几个函数中:

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

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

于 2013-10-10T20:04:01.120 回答
1

我也遇到过类似的问题,我用下面的方法解决,用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));
}

于 2019-12-30T04:24:43.243 回答
0

还没有人谈论过的一种方法是使用一些 JIT 逻辑(我现在不会提供一个工作示例,因为我还没有尝试过,但我会在某个时候将它用于 RPC 库)。这不是严格意义上的 C 语言功能,它仅在 CPU/MCU 架构上可行,您可以在其中写入可执行内存段(在 x86_64、x86、某些 ARM 等上可行)。

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

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

于 2021-05-25T22:29:31.170 回答
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();
}


于 2020-05-11T10:56:48.783 回答