C++无法将参数'1'转换为'void *'为'void *发送(void *)'

C++无法将参数'1'转换为'void *'为'void *发送(void *)'

问题描述:

我在sender类中有startSending过程和一个好友函数(sending)。我想从一个新线程调用好友功能,所以我在startSending程序中创建了一个新线程。C++无法将参数'1'转换为'void *'为'void *发送(void *)'

class sender{ 
    public: 
    void startSending(); 

    friend void* sending (void * callerobj); 
} 

void sender::startSending(){ 
    pthread_t tSending; 
    pthread_create(&tSending, NULL, sending(*this), NULL); 
    pthread_join(tSending, NULL); 
} 

void* sending (void * callerobj){ 
} 

但我得到这个错误

cannot convert ‘sender’ to ‘void*’ for argument ‘1’ to ‘void* sending(void*)’ 

什么是调用pthread_create的从发送正确的方法是什么?

+0

据我记得传递给pthread_create的方法应该是静态的。所以像pthread_create(&tSending,NULL,sender :: sending,NULL);宣布发送静态。 – redobot

+0

@redobot不是。它不能是一个非静态的成员函数,但它当然可以是一个*函数,就像OP的情况一样。 – Angew

+0

@Angew我没有检查文档。但是如果他想要使用类方法,那么应该声明为静态的,如果我没有错。 – redobot

在pthread_create签名如下所示:

int pthread_create(pthread_t *thread, //irrelevant 
        const pthread_attr_t *attr, //irrelevant 
        void *(*start_routine) (void *), //the pointer to the function that is going to be called 
        void *arg); //the sole argument that will be passed to that function 

所以你的情况,该指针sending必须作为第三个参数传递,并this(将传递到sending参数)内斯作为最后一个参数传递:

pthread_create(&tSending, NULL, &sending, this); 

按照documentation of pthread_create,你必须在传递要执行的功能,而不是它的调用:

pthread_create(&tSending, NULL, &sending, this); 

与该线程将调用该函数被作为第四个参数传递给pthread_create的说法,所以在你的情况下它是this

和(虽然这不是对最常见的平台上最实用的编译器实际上是必要的)按规则严格去,因为pthread_create是一个C函数,你发送给它应该有C语言联动太多的功能:

extern "C" void* sending (void * callerobj){ 
} 

pthread_create(&tSending, NULL, sending, this); 

OR

pthread_create(&tSending, NULL, &sending, this);