如何在 C 中转换 void 函数指针?
考虑一下:
#include <stdio.h>
int f() {
return 20;
}
int main() {
void (*blah)() = f;
printf("%d\n",*((int *)blah())()); // Error is here! I need help!
return 0;
}
我想将 'blah' 转换回 (int *),以便我可以将其用作在 printf
语句中返回 20 的函数,但它似乎不起作用。我该如何修复它?
Consider:
#include <stdio.h>
int f() {
return 20;
}
int main() {
void (*blah)() = f;
printf("%d\n",*((int *)blah())()); // Error is here! I need help!
return 0;
}
I want to cast 'blah' back to (int *) so that I can use it as a function to return 20 in the printf
statement, but it doesn't seem to work. How can I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能会修复它:
This might fix it:
您的代码似乎正在调用
blah
指向的函数,然后尝试将其void
返回值转换为int *
,这当然做不到。您需要在调用函数之前强制转换函数指针。在单独的语句中执行此操作可能更清楚,但您可以按照您的要求在 printf 调用中执行此操作:
Your code appears to be invoking the function pointed to by
blah
, and then attempting to cast itsvoid
return value toint *
, which of course can't be done.You need to cast the function pointer before invoking the function. It is probably clearer to do this in a separate statement, but you can do it within the printf call as you've requested:
不要初始化 void 指针并稍后重新转换,而是立即将其初始化为 int 指针(因为您已经知道它是 int 函数):
要在代码中使用它,您只需像这样调用它:
Instead of initializing a void pointer and recasting later on, initialize it as an int pointer right away (since you already know it's an int function):
To use it in your code, you simply call it like so:
typedef
int 版本:typedef
the int version: