[英]Using a function pointer on a non-struct/union
Is there a simpler way to 'bind' a function pointer to an object in C?有没有更简单的方法可以将 function 指针“绑定”到 C 中的 object?
int add_two(int num) {
return num + 2;
}
int main(void)
{
struct thing {
int num;
int (*add_func)(int);
};
struct thing xx = {.num=4, .add_func=add_two};
int yy = xx.add_func(xx.num);
printf("%d", xx.add_func(xx.num));
}
6
6
For example, is it possible to do something like this:例如,是否可以执行以下操作:
int x = 4;
&x->add_two(); // using pseudo-syntax
Or doing it in a single-go, such as:或者一次性完成,例如:
(void*) "7" . add_two(7);
Or is the only way to use a function pointer within the context of a struct or union?或者是在结构或联合上下文中使用 function 指针的唯一方法?
No, there isn't.不,没有。 C++ was invented originally as a preprocessor for C compilers to do this kind of simple "object-oriented" programming paradigm.
C++ 最初是作为 C 编译器的预处理器而发明的,用于执行这种简单的“面向对象”编程范例。
Note that usually you'd want the reference to xx
be passed to the method.请注意,通常您希望将对
xx
的引用传递给该方法。 For that you could use a macro such as为此,您可以使用宏,例如
INVOKE(obj, name, ...) (obj)->name((obj), ## __VA_ARGS__)
Then you can use然后你可以使用
int add_two(thing *this) {
return this->num + 2;
}
...
struct thing {
int num;
int (*add_func)(thing *);
};
...
int yy = INVOKE(&xx, add_func);
...
}
And not need to write the xx
twice;并且不需要两次写
xx
; you could then make it a bit more complicated like put the methods into a separate virtual table object... but all in all that's about as far as you can get with standard C.然后你可以让它变得更复杂一些,比如将这些方法放入一个单独的虚拟表 object ......但总而言之,这就是你可以使用标准 C 所能获得的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.