C:什么是函数指针转换?

C: What even is function pointer conversion?

假设有人想创建一个可以容纳多个函数指针和不同类型的数组..他会怎么做呢?也许一个 void 指针数组可以工作?...事实证明,不,因为为了使用存储在 void 指针中的函数,你必须 convert/cast 它们(void 指针)返回函数指针和...

"A conversion between a function pointer and a void pointer is not possible. void* was never a generic pointer type for function pointers, only for object pointers. They are not compatible types.

[...] you can cast between void* and a function pointer, but what will happen is undefined behavior. You will be relying on system-specific non-standard extensions."

-@Lundin ()

而是...

Slightly better would be to use a function pointer type such as void (*)(void) as the generic pointer. You can convert to/from different function pointers, what will happen is compiler-specific (implementation-defined behavior). That is, the code will still be non-portable, but at least you don't risk a program crash from invoking undefined behavior.

-@Lundin ()


也就是说,从一个函数指针转换为另一个函数指针是什么意思?

谁能解释一下。也许有一个例子。

表示如果你有两种不同的函数指针类型,比如:

int (*i)(int);
void (*v)(void);

然后您可以使用显式强制转换从一种类型转换为另一种类型:

v = (void(*)(void))i;

这是允许的,但调用 v() 将不起作用。标准是这样说的,C17 6.3.2.3 §8:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

因此,如果您尝试通过 v(); 调用该函数,则可能是未定义的行为。但是,您可以转换回原始类型 int(*)(int) 而不会丢失信息。

这允许您使用特定的函数指针类型作为 "generic type"。而不是使用 void*,这是不正确的,正如 .

所讨论的

值得注意的是,如果您使用 typedef,所有带有函数指针的代码都会变得更容易阅读:

typedef int int_func (int);
typedef void void_func (void);

int main() 
{
  int_func*  i;
  void_func* v;

  v = (void_func*) i;

  i = (int_func*) v;
}