如何在C语言中获取函数的函数指针?

4

我有一个C语言函数:

void start_fun()
{
   // do something
}

我想使用 pthread_create() 创建一个线程,并且启动例程为 start_fun(),不修改 void start_fun() 的情况下,如何获得指向 start_fun() 的函数指针。


start_fun是指向start_fun的指针。但是它不是正确类型的函数。pthread_create需要一个void * (*f) (void *) - ArjunShankar
2个回答

6

如果您在代码中任何地方写下没有参数的函数名start_fun,则会获得指向该函数的函数指针。

然而,pthread_create期望一个格式为void* func (void*)的函数。

如果重写函数不是一种选择,那么您将不得不编写一个包装器:

void* call_start_fun (void* dummy)
{
  (void)dummy;

  start_fun();

  return 0;
}

然后将 call_start_fun 传递给 pthread_create:

pthread_create(&thread, NULL, call_start_fun, NULL);

2
该函数不符合 pthread_create 所需的正确类型。 - ArjunShankar
2
这只是一种风格问题,但我会从call_start_fun返回NULL - JeremyP
@JeremyP 不重要,因为结果将是 [任何空指针常量] 转换为 void*,因此该函数将始终返回空指针常量 (void*)0 - Lundin
@ratzip,pthread启动函数必须具有Lundin和我指定的签名。pthread_create()的签名要求如此,如果您不提供它,则您的程序具有未定义的行为,可能涉及崩溃或内存损坏。 - John Bollinger
@ratzip 看这里 - Lundin
显示剩余11条评论

3

函数名称作为表达式使用时,将计算为指向命名函数的指针。例如:

pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, start_fun, NULL);

然而,您提供的start函数没有正确的签名,因此将其用作pthread start函数会产生未定义的行为。start函数必须具有以下签名:

void *start_fun(void *arg);

该函数可能会忽略其参数并总是返回NULL(如果适用的话),但必须声明参数和返回值(具有这些类型)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接