5

这个问题是关于线程的,但我有一个更简单的案例。(初学者)
我在不同的 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;
}
4

2 回答 2

4

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

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

你可以这样做:

  1. 定义一个新类型:

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

    callback = (functiontype)myfunc;
    
于 2013-08-16T16:38:14.953 回答
4

问题是它callback不是一个空指针,它是一个指向函数的指针。因此,要关闭警告,您需要转换为正确的类型:

callback = (void (*)(void *))myfunc;

请注意,这将消除警告,但不能保证有效 - 虽然您可以将函数指针类型转换为不同的函数指针类型,但调用生成的函数指针(无需先将其转换回)是未定义的行为。

现在在大多数机器上,所有指针都具有相同的内部位表示。特别是,MyMsg *并且void *将是相同的,因此这实际上可以正常工作。但它不能保证。要严格符合标准,您应该更改myfunc为:

void myfunc(void *msg_)
{
    MyMsg *msg = (MyMsg *)msg_;
    :

现在它具有与 相同的签名callback,因此您可以在不强制转换的情况下分配它。里面的演员表myfunc可能是一个 noop,但需要在那里严格遵守。

于 2013-08-16T20:39:43.853 回答