我有一个名为 qwerty 的类和一个名为 compute_ans 的函数,它接受一个空指针并返回一个空指针。现在,当我尝试编译时,以下语句会引发错误
pthread_create (thread_a, NULL, compute_ans, (void*) struct_left);
函数的定义是void* compute_ans (void* struct_input)
错误是
cannot convert ‘qwerty::compute_ans’ from type ‘void* (qwerty::)(void*)’ to type ‘void* ()(void)’*
不能将指向非静态成员函数的指针转换为指向函数的指针,C++ 不允许这样做。原因是成员函数采用隐式 this
指针作为参数。从本质上讲,这会将您的函数签名更改为类似于 void* compute_ans(qwerty*, void*)
。为了将函数传递给 pthread_create
,您需要将成员函数设为静态。
class qwerty
{
public:
// ... other member functions and variables ...
// thread start function
static void* compute_ans(void*);
};
如果您不能将其设为静态成员函数,则需要将指向 qwerty
对象的指针传递给线程启动函数。查看问题中的代码,您还需要将其他数据传递给线程函数。为此,您可以使用包含所有必要数据的附加数据结构,并将指针传递给它。
class qwerty; // forward declaration
// Structure passed to pthread_create and our helper function
struct thread_data
{
qwerty* qptr; // pointer to qwerty object
void* data; // pointer to other data. change void to your data type.
};
class qwerty
{
public:
// thread start function
static void* start_compute_ans(void* param)
{
// get a pointer to the thread data
thread_data* tdata = static_cast<thread_data*>(param);
// Call the real compute_ans
tdata->qptr->compute_ans(tdata->data);
// Delete the data (use an appropriate smart pointer if possible)
delete tdata;
return NULL;
}
// the real
void compute_ans(void*)
{
// do stuff here
}
};
// Create our thread startup data
thread_data* tdata = new thread_data();
tdata->qptr = qwerty_pointer;
tdata->data = struct_left;
// start the thread data
pthread_create (thread_a, NULL, &qwerty::start_compute_ans, tdata);