簡體   English   中英

從'void *'到'void *(*)(void *)'c ++的無效轉換?

[英]invalid conversion from ‘void*’ to ‘void* (*)(void*)’ c++?

我試圖使用pthread_create()但它總是給我這個錯誤無效轉換從void*void* ( * )(void*)

此錯誤在第3個參數中。 有人可以幫我解決這個錯誤嗎?

void Print_data(void *ptr) {
    cout<<"Time of Week = " <<std::dec<<iTOW<<" seconds"<<endl;
    cout<<"Longitude = "<<lon<<" degree"<<endl;
    cout<<"Latitude  = "<<lat<<" degree"<<endl;
    cout<<"Height Above Sea = "<<alt_MSL<<" meters"<<endl;    
  }

int call_thread() 
  {
    pthread_create(&thread, NULL, (void *) &Print_data, NULL);
    return 0;
  }

pthread_create需要該參數的函數指針時,錯誤是您將函數指針( void* (*)(void*) )轉換為對象指針( void* )。 沒有隱式轉換來撤消你已經完成的狡猾的轉換,因此錯誤。

答案是不這樣做:

pthread_create(&thread, NULL, &Print_data, NULL);

並且您還需要修改Print_data以返回void*以匹配Posix線程接口:

void *Print_data(void *ptr) {
    // print stuff
    return NULL;  // or some other return value if appropriate
}

正如評論中所指出的,直接從C ++使用這個C庫還有其他各種問題。 特別是,為了便於攜帶,線程入口函數應該是extern "C" 就個人而言,我建議使用標准的C ++線程庫(或Boost的實現,如果你堅持使用2011年之前的語言版本)。

您正在嘗試將函數指針轉換為void* here: (void *) &Print_data

根據pthread_create你需要傳入一個帶有void*的函數並返回一個void*

所以你的功能簽名應該是

void* Print_data(void *ptr) 

你的電話應該是

pthread_create(&thread, NULL, &Print_data, NULL);

pthread_create將第三個參數作為

int pthread_create(pthread_t *thread,
                   const pthread_attr_t *attr,
                   void *(*start_routine)(void*),
                   void *arg);

這, void *(*start_routine)(void*)是一個指向函數的指針,該函數接受void*指針並返回void*指針。

當您執行&Print_data並將指針轉換為void * ,這意味着您傳遞的是void*類型的指針,而不是類型為void *(*start_routine)(void*) [函數指針]的指針。

要正確,您需要將返回類型設置為void*並將調用作為pthread_create(&thread, NULL, &Print_data, NULL);

你必須返回void*

void* Print_data(void *ptr) {

滿足需求。

要傳遞的函數的簽名是

void* function(void*);

然后使用調用pthread_create

 pthread_create(&thread, NULL, &Print_data, NULL);

添加頭文件#include並編譯g ++ -lpthread

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM