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

标签 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;
}

最佳答案

是的,你的类型转换是错误的:

 callback = (void*)myfunc;
              ^
               is void*  but Not void (*)(void*)

你可以这样做:

  1. 定义一个新类型:

    typedef  void (*functiontype)  ( void*);
    
  2. 类型转换如下:

    callback = (functiontype)myfunc;
    

关于c++ - 从 void* 到 void(*)(void*)[-fpermissive] 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278127/

相关文章:

c++ - 错误 C2440 : '=' : cannot convert from 'int *' to 'int **'

c++ - 从 DLL 导出 STL std::basic_string 模板时,出现 LNK2005 错误

C编程子进程未执行

c++ - 什么是 std::false_type 或 std::true_type?

c - 如何在C中使用12位数字?

c++ - 这种尺寸对齐是如何工作的

c - 访问结构中的字符指针字段

c++ - 类型转换时 *(int*)&x 是什么意思?

c++ - 程序因二进制错误而停止

c++ - 从无序关联容器中移动对象