[英]invalid conversion from void* to void(*)(void*)[-fpermissive]
this question was asked in relation to threads, but I have a simpler case.(beginner) 这个问题是关于线程的问题,但我有一个更简单的案例。(初学者)
I tried the code in different compilers for c++ but would not work. 我在c ++的不同编译器中尝试了代码,但是无法工作。
please advise how to replace the line: callback = (void*)myfunc;
请告知如何替换该行:
callback = (void*)myfunc;
//--> error
// - >
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;
}
The problem is that callback
is not a void pointer, its a pointer to a function. 问题是
callback
不是一个void指针,它是一个指向函数的指针。 So to shut up the warning, you need to cast to the correct type: 因此,要关闭警告,您需要转换为正确的类型:
callback = (void (*)(void *))myfunc;
Note that this will get rid of the warning, but is not guaranteed to work -- while you can cast a function pointer type to a different function pointer type, calling the resulting function pointer (without first casting it back) is Undefined Behavior. 请注意,这将消除警告,但不能保证工作 - 虽然您可以将函数指针类型强制转换为其他函数指针类型,但调用结果函数指针(不先将其强制转换)是未定义行为。
Now on most machines, all pointers have the same internal bit representation. 现在在大多数机器上,所有指针都具有相同的内部位表示。 In particular,
MyMsg *
and void *
will be the same, so this will in fact work fine. 特别是,
MyMsg *
和void *
将是相同的,所以这实际上工作正常。 But its not guaranteed. 但它不能保证。 To be strictly standards conforming, you should change
myfunc
to be: 要严格遵守标准,您应该将
myfunc
更改为:
void myfunc(void *msg_)
{
MyMsg *msg = (MyMsg *)msg_;
:
Now it has the same signature as callback
, so you can assign it without casting. 现在它具有与
callback
相同的签名,因此您可以在不进行转换的情况下进行分配。 The cast inside myfunc
is probably a noop, but needs to be there for strict conformance. myfunc
可能是一个noop,但需要严格遵守。
Yes, your typecasting is wrong: 是的,你的类型转换是错误的:
callback = (void*)myfunc;
^
is void* but Not void (*)(void*)
You can do like: 你可以这样做:
Define a new type: 定义新类型:
typedef void (*functiontype) ( void*);
Typecast as follows: Typecast如下:
callback = (functiontype)myfunc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.