【发布时间】:2016-02-20 10:36:28
【问题描述】:
我正在使用我的教授提供的库来完成课堂作业,因此我不能透露太多我的代码。以下是 API 的一部分:
typedef void (*thread_startfunc_t) (void*);
int thread_libinit(thread_startfunc_t func, void *arg);
int thread_create(thread_startfunc_t func, void *arg);
thread_libinit initializes the thread library. A user program should call
thread_libinit exactly once (before calling any other thread functions).
thread_libinit creates and runs the first thread. This first thread is
initialized to call the function pointed to by func with the single
argument arg. Note that a successful call to thread_libinit will not
return to the calling function. Instead, control transfers to func, and
the function that calls thread_libinit will never execute again.
thread_create is used to create a new thread. When the newly created
thread starts, it will call the function pointed to by func and pass it the
single argument arg.
为了测试我写了以下代码:
void pHello(int i)
{
cout << "Hello from thread " << i << endl;
}
... [In Main] ...
typedef void (*thread_startfunc_t) (void* i);
thread_startfunc_t pSalute = & pHello; //Does not compile
thread_libinit(pSalute,1);
我收到错误:
In function `int main(int, char**)`:
error: invalid conversion from `void (*) (int)' to `thread_startfunc_t{aka void(*) (void*)}' [-fpermissive]
我认为 void 指针变量可以指向任何变量。那么为什么它不能指向函数 pHello 的 int 呢?如何将函数分配给函数指针?
【问题讨论】:
标签: c++ void-pointers