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

标签 c type-conversion function-pointers

<分区>

假设有人想创建一个可以容纳多个函数指针和不同类型的数组..他会怎么做呢?也许一个 void 指针数组可以工作?......事实证明,不,因为为了使用存储在 void 指针中的函数,你必须将它们(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 (here)

相反...

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 (here)


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

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

最佳答案

这意味着如果你有两个不同的函数指针类型,例如:

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) 而不会丢失信息。

这允许您将特定的函数指针类型用作“通用类型”。而不是使用 void*,这是不对的,正如所讨论的 here .


值得注意的是,如果使用 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;
}

关于C:什么是函数指针转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073223/

相关文章:

python - 替换数据框中格式不正确的值

c - 字符串创建时的段错误

c - 通过静态分析查找 C 项目中未使用的函数

c - 编译 *.cc 文件时出现 Gcc 编译错误

c++ - 避免被无符号整数除法签名

c++ - 如何在不转换回基类类型的情况下返回其派生类型的对象?

C++ std::function 语法问题

c++ - 如果余弦是 fptr,如何解析 *(void **) (&cosine)

c++ - 这是实现自定义事件处理程序的正确方法吗?

c - if (!strcmp() ... 中的感叹号有什么作用?