将{指针指向具有C链接的函数}指向{指向具有C ++链接的函数},反之亦然 [英] Assigning {pointer to function with C linkage} to {pointer to function with C++ linkage} and vice versa

查看:140
本文介绍了将{指针指向具有C链接的函数}指向{指向具有C ++链接的函数},反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否合法?

extern "C" typedef void (ft_blah_c)();
/*extern "C++"*/ typedef void (ft_blah_cpp)();

extern "C" void fn_blah_c() {}
/*extern "C++"*/ void fn_blah_cpp() {}

ft_blah_c *g_Blah_c = fn_blah_cpp; // <--- ?
ft_blah_cpp *g_Blah_cpp = fn_blah_c; // <--- ?

我有类似的配置的实际代码,它编译和执行没有任何问题(MSVC 2010)。

I have real code with similiar assigments, it compiles and executes without any problems (MSVC 2010).

推荐答案

一般来说不应该工作。问题是当你直接调用 fn_blah_c fn_blah_cpp 时,编译器知道使用的调用约定,但是如果你把它们存储在一个函数指针,编译器只看到那个指针,只能使用函数指针的类型来决定如何传递参数和返回类型。

In general that should not work. The problem is that when you call fn_blah_c or fn_blah_cppdirectly the compiler knows the function and the calling conventions to use, but if you store those in a function pointer the compiler only sees that pointer and can only use the type of the function pointer to determine how to pass the arguments and return types.

如果C和C ++的调用约定在您的环境中是相同的,那么它可以工作(这可能是为什么你的编译器允许它),但这不是一般情况下和分配应该失败。

If the calling convention for C and C++ are the same in your environment then it can work (and that is probably why your compiler is allowing it), but that is not the case in general and the assignment should fail.

这篇关于将{指针指向具有C链接的函数}指向{指向具有C ++链接的函数},反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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