C链接传递给C库函数指针 [英] C linkage for function pointer passed to C library
问题描述
我的情况是pretty简单:我想我的C ++程序来处理Unix的信号。要做到这一点,glibc的提供signal.h中的函数叫做的sigaction
,它预计将收到一个函数指针作为其第二个参数。
的externC
{
无效uponSignal(INT);
}无效uponSignal(INT)
{
//设置一些标志来退出程序
}静态的
无效installSignalHandler()
{
//初始化信号处理程序
静态结构的sigaction sighandler;
memset的(安培; sighandler,0,sizeof的(结构的sigaction));
sighandler.sa_handler = uponSignal; //安装
的sigaction(SIGINT,和放大器; sighandler,nullptr);
}
我的问题是:在的externC
联动符必要
奖金问题:可以uponSignal声明静态
我的问题是:在
?的externC
联动符必要
块引用>有关最大的可移植性,是的; C ++标准只能通过声明
的externC
。功能保证了用C互操作性实际上,没有;最明智的ABI(包括glibc的使用的GNU ABI)将使用C和C ++非成员相同的调用约定(和静态成员)功能,让
的externC
只需要共享语言之间的函数名。
奖金的问题:能
?uponSignal
声明为static
块引用>是的。只需要外部链接从其他翻译单元名称来访问功能;这是没有必要通过一个函数指针调用的函数。
My case is pretty simple: I want my C++ program to deal with Unix signals. To do so, glibc provides a function in signal.h called
sigaction
, which expects to receive a function pointer as its second argument.extern "C" { void uponSignal(int); } void uponSignal(int) { // set some flag to quit the program } static void installSignalHandler() { // initialize the signal handler static struct sigaction sighandler; memset( &sighandler, 0, sizeof(struct sigaction) ); sighandler.sa_handler = uponSignal; // install it sigaction( SIGINT, &sighandler, nullptr ); }
My question is: is the
extern "C"
linkage specifier necessary?Bonus question: can uponSignal be declared
static
?解决方案My question is: is the
extern "C"
linkage specifier necessary?For maximum portability, yes; the C++ standard only guarantees interoperability with C via functions declared
extern "C"
.Practically, no; most sensible ABIs (including the GNU ABI used by glibc) will use the same calling convention for C and C++ non-member (and static member) functions, so that
extern "C"
is only needed to share the function name between languages.Bonus question: can
uponSignal
be declared static?Yes. External linkage is only needed to access the function by name from other translation units; it's not necessary to call the function via a function pointer.
这篇关于C链接传递给C库函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!