[英]Auto cast of void* argument in function pointer
Following code works fine, however I was wondering if this is valid use of rule that void* is compatible with any other pointer以下代码工作正常,但是我想知道这是否是对 void* 与任何其他指针兼容的规则的有效使用
#include <stdio.h>
typedef struct {
int foo;
} SomeStruct_t;
typedef void(*SomeFunction_t)(void* ptr);
void bar(SomeStruct_t* str) {
printf("%d\n", str->foo);
}
void teddy(void* anyPtr) {
SomeStruct_t* str = (SomeStruct_t*)anyPtr;
printf("%d\n", str->foo);
}
int main()
{
SomeFunction_t functPtr = (SomeFunction_t)bar;
SomeStruct_t data = {.foo = 33};
functPtr(&data);
functPtr = teddy;
functPtr(&data);
return 0;
}
Question is, should I use bar
or teddy
variant?问题是,我应该使用
bar
还是teddy
变体? I prefer bar
but I'm not sure if for some corner cases this might lead to hard to detect problem.我更喜欢
bar
但我不确定在某些极端情况下这是否会导致难以检测到的问题。
This is not valid:这是无效的:
SomeFunction_t functPtr = (SomeFunction_t)bar;
Because you're casing a function pointer of type void (*)(SomeStruct_t*)
to type void (*)(void*)
and subsequently calling it though the casted type.因为您将
void (*)(SomeStruct_t*)
类型的 function 指针封装为void (*)(void*)
类型,然后通过强制类型调用它。 The function pointer types are not compatible because the parameters are not compatible. function 指针类型不兼容,因为参数不兼容。 This triggers undefined behavior .
这会触发未定义的行为。
While a SomeStruct_t *
can be converted to a void *
, that conversion can't happen because the casted function pointer prevents it.虽然
SomeStruct_t *
可以转换为void *
,但这种转换不会发生,因为强制转换的 function 指针会阻止它。 There's no guarantee that SomeStruct_t *
and void *
have the same representation.不能保证
SomeStruct_t *
和void *
具有相同的表示。
Using the function teddy
which matches the function pointer type is safe.使用与 function 指针类型匹配的 function
teddy
是安全的。 Also, you don't need to cast the parameter to SomeStruct_t *
inside the function because conversions to/from void *
don't require one in most cases.此外,您不需要在 function 中将参数强制转换为
SomeStruct_t *
,因为在大多数情况下,与void *
的转换不需要一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.