这个问题是关于线程的,但我有一个简单的例子。(初学者)
我在不同的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;
}发布于 2013-08-16 16:38:14
是的,你的打字是错误的:
callback = (void*)myfunc;
^
is void* but Not void (*)(void*)你可以这样做:
发布于 2013-08-16 20:39:43
问题是callback不是一个空指针,它是一个指向函数的指针。因此,要关闭警告,需要转换为正确的类型:
callback = (void (*)(void *))myfunc;请注意,这将消除警告,但不能保证工作--虽然您可以将函数指针类型转换为不同的函数指针类型,但调用结果函数指针(不首先将其转换回函数指针)是未定义的行为。
现在,在大多数机器上,所有指针都有相同的内部位表示。特别是,MyMsg *和void *将是相同的,因此这实际上会很好。但这不能保证。要严格遵循标准,您应该将myfunc更改为:
void myfunc(void *msg_)
{
MyMsg *msg = (MyMsg *)msg_;
:现在它具有与callback相同的签名,因此您可以在不进行转换的情况下分配它。myfunc内部的强制转换可能是一个noop,但需要严格遵守。
https://stackoverflow.com/questions/18278127
复制相似问题