从 void* 到 void(*)(void*)[-fpermissive] 的无效转换

Alf*_*red 5 c c++ pointers function-pointers

这个问题是关于线程提出的,但我有一个更简单的案例。(初学者)
我在不同的编译器中尝试了 C++ 的代码,但不起作用。
请告知如何替换该行: callback = (void*)myfunc;//-->error

typedef struct _MyMsg {
        int appId;
        char msgbody[32];
} MyMsg;    
void myfunc(MyMsg *msg)
{
        if (strlen(msg->msgbody) > 0 )
                printf("App Id = %d \n Msg = %s \n",msg->appId, msg->msgbody);
        else
                printf("App Id = %d \n Msg = No Msg\n",msg->appId);
}    
/*
 * Prototype declaration
 */
void (*callback)(void *);    
int main(void)
{
        MyMsg msg1;
        msg1.appId = 100;
        strcpy(msg1.msgbody, "This is a test\n");    
        /*
         * Assign the address of the function 'myfunc' to the function
         * pointer 'callback'
         */                 
//line throws error: invalid conversion from void* to void(*)(void*)[-fpermissive]    
        callback = (void*)myfunc; //--> error               
        /*
         * Call the function
         */
        callback((MyMsg*)&msg1);    
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gri*_*han 4

是的,你的打字是错误的:

 callback = (void*)myfunc;
              ^
               is void*  but Not void (*)(void*)
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

  1. 定义一个新类型:

    typedef  void (*functiontype)  ( void*);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 类型转换如下:

    callback = (functiontype)myfunc;
    
    Run Code Online (Sandbox Code Playgroud)