C函数指针铸造空指针 [英] C function pointer casting to void pointer

查看:109
本文介绍了C函数指针铸造空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行下面的程序,但得到一些奇怪的错误:

I am trying to run the following program but getting some strange errors:

文件1.C:

typedef unsigned long (*FN_GET_VAL)(void);

FN_GET_VAL gfnPtr;

void setCallback(const void *fnPointer)
{
    gfnPtr = *((FN_GET_VAL*) (&fnPointer));
}

文件2.C:

extern FN_GET_VAL gfnPtr;

unsigned long myfunc(void)
{
    return 0;
}

main()
{
   setCallback((void*)myfunc);
   gfnPtr(); /* Crashing as value was not properly 
                assigned in setCallback function */
}

下面的gfnPtr()是当用gcc编译64位的SUSE Linux崩溃。但它成功地调用gfnPtr()VC6和SunOS。

Here the gfnPtr() is crashing on 64-Bit suse linux when compiled with gcc. But it successfully calling gfnPtr() VC6 and SunOS.

但是,如果我改变,因为下面给出的函数,它是成功的工作。

But if I change the function as given below, it is working successfully.

void setCallback(const void *fnPointer)
{
    int i; // put any statement here
    gfnPtr = *((FN_GET_VAL*) (&fnPointer));
}

请与问题的原因有所帮助。谢谢你。

Please help with the cause of problem. Thanks.

推荐答案

标准不允许投函数指针无效* 。您只可以转换为另一种函数指针类型。 6.3.2.3§8:

The standard does not allow to cast function pointers to void*. You may only cast to another function pointer type. 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

重要的是,必须使用指针调用函数之前转换回原始类型(从技术上说,到兼容类型定义的兼容的6.2.7)。

Importantly, you must cast back to the original type before using the pointer to call the function (technically, to a compatible type. Definition of "compatible" at 6.2.7).

这篇关于C函数指针铸造空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆