简体   繁体   English

如何在 C 中强制转换 void 函数指针?

[英]How can I cast a void function pointer in C?

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.我想将 'blah' 转换回 (int *) 以便我可以将它用作函数以在printf语句中返回 20,但它似乎不起作用。 How can I fix it?我该如何解决?

这可能会解决它:

printf("%d\n", ((int (*)())blah)() ); 

Your code appears to be invoking the function pointed to by blah , and then attempting to cast its void return value to int * , which of course can't be done.您的代码似乎正在调用blah指向的函数,然后尝试将其void返回值转换为int * ,这当然无法完成。

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:在单独的语句中执行此操作可能更清楚,但您可以根据要求在 printf 调用中执行此操作:

printf("%d\n", ((int (*)())blah)() );

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):与其初始化一个 void 指针并稍后重铸,不如立即将其初始化为一个 int 指针(因为您已经知道它是一个 int 函数):

int (*blah)() = &f; // I believe the ampersand is optional here

To use it in your code, you simply call it like so:要在您的代码中使用它,您只需像这样调用它:

printf("%d\n", (*blah)());

typedef the int version: typedef int 版本:

typedef int (*foo)();

void (*blah)() = f;
foo qqq = (foo)(f);

printf("%d\n", qqq());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM