所以我有一个类型为 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/