C函数指针类型的兼容性 [英] C function pointer type compatibility

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

问题描述

编写与函数回调工作的图书馆,我经常键入铸(叫)函数指针类型具有相同的调用约定和相同的签名,但有一个例外:他们有指向不同类型的参数(全数据),或空指针。

最近,我发现它可能不是那么安全的,根据这个:<一href=\"http://stackoverflow.com/a/14044244/3079266\">http://stackoverflow.com/a/14044244/3079266

基本上,我的理解是,如果参数类型是兼容的,这意味着函数指针类型也是兼容的,并且应该没有问题。

现在,我有三个问题。

第一:这是否意味着,由于指向不同类型的在技术上是不兼容的,我在做什么会导致未定义的行为

第二:在哪里(什么架构)我能摆脱它?是其中的Windows x86或x64版本?

第三:?在这里我不能逃脱它


解决方案

  1. 是的,这是UB本身

  2. 您也许可以逃脱这种非优化的非调试版本。优化器可以利用指针类型的要弄清楚两个指针是否可以别名,如果你撒谎的实际类型可能失败的逻辑。调试版本,当然可以只彻底检查,如果有一个类型不匹配。

  3. Windows不是一个编译器,这样,是不是一个合理的问题。常见的Windows编译器做优化构建,以及ICC尤其是已知有先进的优化。

Writing a library that works with function callbacks, I've frequently type-casted (and called) function pointers to types with the same calling convention and same signatures, but with one exception: they had parameters pointing to different types (all data), or void pointers.

Recently, I discovered that it might not be that safe, according to this: http://stackoverflow.com/a/14044244/3079266

Basically, as I understood it, if the types of the arguments are compatible, that means the function pointer types are also compatible, and there should be no problem.

Now, I've got 3 questions.

First: does this mean that, since pointers to different types are technically incompatible, what I am doing can cause undefined behaviour?

Second: where (on what architectures) can I get away with it? Are Windows x86 or x64 versions among them?

Third: where can I NOT get away with it?

解决方案

  1. Yes, this is UB by itself
  2. You probably can get away with this in non-optimized non-debug builds. An optimizer may take advantage of pointer types to figure out whether two pointers can be aliased, logic which may fail if you're lying about the actual types. Debug builds of course can just check outright if there's a type mismatch.
  3. Windows is not a compiler, so that's not a sensible question as-is. Common Windows compilers do optimize builds, and ICC especially is known to have advanced optimizations.

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

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