C function pointer type compatibility

雨燕双飞 提交于 2019-12-13 17:00:38

问题


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: https://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:


  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.


来源:https://stackoverflow.com/questions/27767392/c-function-pointer-type-compatibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!