c - 有什么方法可以在 C 中执行类似 std::bind 的操作吗?

标签 c function function-pointers

所以我有一个类型为 void (*actionOnM)(void * myTypeInstance) 的函数,我需要将其包装并作为 void (*action)()。在 C 中这样的事情可能吗?

最佳答案

您通常可以按照以下规则将(简单的)C++ 翻译成 C 语言:

  • 一个 C++ 类在 C 中变成一个只包含属性(没有方法)的结构
  • C++ 方法是将指向对象(此处为结构)的指针作为第一个参数的 C 函数

这里是你的数据:

  • 指向接受 void * 参数并返回 void 的函数的指针
  • 指向参数的指针

但是您不会将它作为指向函数的指针传递,而是作为指向结构的指针传递:

typedef struct _binder {
    void (*action)(void *param);
    void *param;
} binder;

当你想绑定(bind) actionOnM(&myTypeInstance) 时,你只需这样做:

binder *bind = malloc(sizeof(binder));
bind->action = &actionOnM;
bind->param = &myTypeInstance;

然后您可以将绑定(bind)函数作为单个参数 bind 传递:

void otherFunct(binder *bind, int otherParam) {
    /* ... */
    bind->action(bind->param); /* actual call to bound function */
    /* ... */
}

当然还有 free(bind) :-)

如果你想让所有这些都更接近 C++ 方式,只需定义一个执行函数:

void bind_call(binder *bind) {
    bind->action(bind->param);
}

其他函数将变成:

void otherFunct(binder *bind, int otherParam) {
    /* ... */
    bind_call(bind); /* actual call to bound function */
    /* ... */
}

关于c - 有什么方法可以在 C 中执行类似 std::bind 的操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868185/

相关文章:

c - 在 macOS 内核扩展中有效地使用同步

c - 通过 execlp 函数传递参数时出现问题 - C

math - 绘制2D隐式标量场的等值线

azure - 尝试了解 Azure Durable Function 上下文

c++ - 使用函数指针进行结构初始化

c - 具有通用参数类型的函数指针

c - 为什么我在 C 语言中收到从 'char' 到 'const char"的无效转换错误

c - HEX码扫描和处理

python - Python 中的函数声明

C++推导成员函数参数