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

use*_*ood 6 c pointers arguments bind function

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

由于我对 C 编程还很陌生,所以这个问题可能看起来有点愚蠢(或者很容易回答),但在互联网上,我只是找到了有关 C++ 的示例,而这不是我要搜索的内容。

这是我想展示的一个例子,以便您可以轻松理解我的问题:

try.h 文件:

struct thing {
  void (*a)(int, int);
};
void add(int x, int y);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

作为一个例子,我希望有always x = 2,所以函数指针struct thing将是这种类型的指针:void (*a)(int)而不是void (*a)(int, int)了。

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

Joh*_*ode 6

函数指针必须具有与其指向的函数相同的签名(类型和参数),因此您不能真正这样做。

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

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 );
}
Run Code Online (Sandbox Code Playgroud)

您可能想尝试一下,但这应该可以帮助您开始。