【问题标题】:What is a worker in C?什么是 C 中的工人?
【发布时间】:2013-03-16 01:00:22
【问题描述】:

我正在查看ss 命令代码,我看到一个函数似乎将一个函数作为参数传递给另一个函数。但我认为这样做的方法是声明一个指向函数的指针。在代码中,他们执行以下操作:

generic_record_read(fp, tcp_show_line, f, AF_INET6).

该函数的原型是:

static int generic_record_read(FILE *fp,
               int (*worker)(char*, const struct filter *, int),
               const struct filter *f, int fam);

我认为作为参数传递给generic_record_read 的函数是tcp_show_line,原型是:

static int tcp_show_line(char *line, const struct filter *f, int family)

我不明白将generic_record_read中的参数tcp_show_line声明为int (*worker)(char*, const struct filter *, int)的方式

类型(char*, const struct filter *, int)对应tcp_show_line的参数,但前面有int (*worker)

似乎这是一种将函数作为参数传递的方式,因为在generic_record_read 的实现中,worked 被用作函数tcp_show_line,但我已经没见过这样的:

static int generic_record_read(FILE *fp,
               int (*worker)(char*, const struct filter *, int),
               const struct filter *f, int fam)
{
//....

    if (worker(line, f, fam) < 0)
        return 0;
//.....
}

我错了吗?

【问题讨论】:

  • 它只是一个作为参数传递的函数指针。 worker 是他们选择的名称。

标签: c function function-pointers worker


【解决方案1】:

正如您所料,worker 是一个函数指针,当被调用时,它接受以下参数:char*, const struct filter *, int。如果您以前没有见过这些,那么您显然没有使用过qsortbsearch,它们是用于排序和搜索的标准C 函数。这种抽象在 C 语言中非常有用。

【讨论】:

    【解决方案2】:
    int (*worker)(char*, const struct filter *, int)
    

    worker 是一个指向函数的指针,该函数接受参数列表(char *, const struct filter *, int) 并返回int。那是你的问题吗?

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多