声明回调函数和返回类型

时间:2013-07-05 17:25:18

标签: pointers callback

在以下函数中,对于回调函数start_routine,返回类型为void **

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
               void *(*start_routine) (void *), void *arg);

但是当我们定义回调函数时,它是这样的:

void func(void *)

我知道这是一个函数,但我认为至少回调函数应该是这样的:

void* func(void *);
我错了吗?谢谢!

1 个答案:

答案 0 :(得分:0)

void func(void *)只是一个普通的函数,它不返回任何内容并且需要void*。它不能作为函数的参数放置。

void* func(void *)与上面类似,唯一的区别是它返回void*指针。

回调函数看起来像这个return_type (*function_name)(arguments)。这里,一个例子是void* (*start_routine)(void *)。这是有效函数参数。

pthread_create函数将第二个参数作为指向函数start_routine的指针,该函数的返回类型为void*且只有一个类型为void*的参数。

此页面的摘录:http://www.cprogramming.com/tutorial/function-pointers.html

有时人们会在投入更多明星时感到困惑:

void *(*foo)(int *);

这里的关键是要从里到外阅读;请注意表达式的最内层元素是*foo,否则它看起来像一个普通的函数声明。 *foo应该引用一个返回void*并取int*的函数。因此,foo是指向这样一个函数的指针。