gpt4 book ai didi

c++ - 在使用 pthreads 时,如何在 C++ 中将方法指针作为函数参数传递

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:53 25 4
gpt4 key购买 nike

我有一个与 C++ 和线程相关的问题。我对 Java 比 C++ 更熟悉,这个错误让我很困惑。

想象一下,在 x.h 文件中我有一个类,例如:

class A{

public A();

public virtual void* func(void*);

public virtual void func2();

public virtual void func3();

};

在 x.cpp 文件中我想这样做:

void* A::func(void*) {

while(....)
func2();

return NULL;
}

void A::func2() {

...some stuff there...

}

void A::func3() {

pthread_t t1;

pthread_create(&t1, NULL, &A::func, NULL);

void* result;

pthread_join(t1,&result);

...some other stuff...

}

问题是它因以下错误而挂起:

"error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function."

我应该怎么做才能解决这个问题?

谢谢。

最佳答案

这是一条糟糕的错误消息,但从根本上说它试图告诉您的是您不能从实例方法形成函数指针(我不确定这里的 Java 术语是什么)。这是因为要调用实例方法,您需要实际代码的地址和对象的地址都是 this,而常规函数指针只存储前者。

您在这里需要的是一个 static 包装器方法,它符合 pthread_create 对线程启动例程的期望。您将 this 作为第四个参数传递给 pthread_create,包装器将其参数转换回对象指针并调用 func。这种类型的包装器通常称为“thunk”,因为它使一种调用约定适应另一种调用约定。

class A {
// ...
static void* thread_start_thunk(void* self);
};

void*
A::thread_start_thunk(void* self)
{
return static_cast<A*>(self)->func();
}

// ...

void
A::func3()
{
// ....
pthread_create(&t1, 0, &A::thread_start_thunk, static_cast<void*>(this));
// ...
}

转换是不可避免的。

关于c++ - 在使用 pthreads 时,如何在 C++ 中将方法指针作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13725551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com