c - 如何阅读这个原型(prototype)?

标签 c prototype function-pointers declaration

帮助我理解以下原型(prototype)。最后一个 (int) 在做什么?

void ( *signal(int sig, void (*handler)(int)) ) (int);

最佳答案

找到最左边的标识符并找出路,记住 []()* 之前绑定(bind); IOW,*a[] 是指针数组,(*a)[] 是指向数组的指针,*f()是一个返回指针的函数,(*f)() 是一个指向函数的指针。因此,

void ( *signal(int sig, void (*handler)(int)) ) (int);

分解为

        signal                                          -- signal
        signal(                               )         -- is a function
        signal(    sig                        )         -- with a parameter named sig
        signal(int sig,                       )         --   of type int
        signal(int sig,        handler        )         -- and a parameter named handler
        signal(int sig,       *handler        )         --   which is a pointer
        signal(int sig,      (*handler)(   )) )         --   to a function
        signal(int sig,      (*handler)(int)) )         --   taking an int parameter
        signal(int sig, void (*handler)(int)) )         --   and returning void
       *signal(int sig, void (*handler)(int)) )         -- returning a pointer
     ( *signal(int sig, void (*handler)(int)) )(   )    -- to a function
     ( *signal(int sig, void (*handler)(int)) )(int)    --   taking an int parameter
void ( *signal(int sig, void (*handler)(int)) )(int);   --   and returning void

signal 函数将一个信号 (sig) 与一个回调函数 (handler) 关联起来,就像这样:

#include <signal.h>

static int interrupt = 0;

/**
 * The following function will be called when a SIGINT is
 * detected (such as when someone types Ctrl-C)
 */
void interrupt_handler( int sig )
{
  interrupt = 1;
}

int main( void )
{
  /**
   * Declare a pointer to the old interrupt handler function
   */
  void (*old_interrupt_handler )(int);

  /**
   * Save the old interrupt handler while setting the new one
   */
  old_interrupt_handler = signal( SIGINT, interrupt_handler );
  while ( !interrupt )
  {
    // do stuff until someone hits Ctrl-C
  };

  /**
   * restore the original interrupt handler
   */
  signal( SIGINT, old_interrupt_handler );
  return 0;
}

关于c - 如何阅读这个原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739500/

相关文章:

python - 有条件的 `ctypedef` 与 Cython

python - 使用 ctypes 调用指向定义为静态的函数的函数指针

javascript - 使用 JavaScript 制作原型(prototype)拼图

c - 函数指针位置未通过

c - 如何在纯 C 中包装函数指针

c - GCC 链接器 : move a symbol in a specified section

C套接字问题-随机客户端地址和端口号

Javascript : Modifying Prototype doesn't affect existing Instances

javascript - 如何停止通过引用传递原型(prototype)中存储的对象?

从主函数调用结构值时无法打印值