C++ 如何将函数分配给接受void*类型参数的函数指针?

C++ 如何将函数分配给接受void*类型参数的函数指针?,c++,void-pointers,C++,Void Pointers,我正在使用我的教授为课堂作业提供的库,所以我不能透露太多的代码。以下是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.

我正在使用我的教授为课堂作业提供的库,所以我不能透露太多的代码。以下是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); 

我认为空指针变量可以指向任何变量。那么为什么它不能指向函数pHello的int呢?如何将函数分配给函数指针?

具有特定签名(返回类型加变量类型)的函数指针只能指向具有相同签名的函数

在您的情况下,似乎无法更改函数指针类型,您可以根据

void pHello(void* i)
{
   std::cout << "Hello from thread " << *static_cast<int*>(i) << std::endl;
}

typedef void (*thread_startfunc_t) (void*);

int main()
{
    thread_startfunc_t f = pHello;

    //or point to a non-capturing lambda:
    thread_startfunc_t f2 = [](void *) { std::cout<<"hi"<<std::endl; };
}
void pHello(void*i)
{
标准::cout
我认为一个空指针变量可以指向任何变量。那为什么呢
它不能指向函数pHello的int吗

因为语句不正确。在C++中,必须使用cask来实现这一点。这是C++和C之间的最大区别之一。 <>你可以测试这个。编译你的代码为C,删除C++特性,比如<代码> <代码>,它应该按照预期工作。< /P> 我如何分配一个任务 函数指向函数指针

将pHello的签名更改为:

void pHello(void*)
在函数内部,必须使用强制转换来获取指针对象的值

另外,当调用
thread\u libinit
时,第二个参数必须是
int
对象的地址,该对象在函数返回之前一直有效


当然,这些都不是很好的或现代的C++。你的教授的API应该使用<代码> STD::函数< /C> >。/P>你添加了(几乎肯定)猜测为什么会发生这个错误,+1。
void pHello(void*)