2009-08-11 163 views
1

如何創建一個靜態成員函數的線程例行_beginthreadex靜態成員函數

class Blah 
{ 
    static void WINAPI Start(); 
}; 

// .. 
// ... 
// .... 

hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); 

這給了我下面的錯誤:

***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'*** 

我在做什麼錯?

回答

16

有時,它讀取你得到的錯誤是非常有用的。

cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)' 

讓我們看看它說什麼。對於參數3,您給它一個帶簽名void(void)的函數,即一個不帶參數的函數,並且不返回任何內容。它無法將其轉換爲unsigned int (__stdcall *)(void *),這是_beginthreadex預計

該公司預計其功能:

  • 返回一個unsigned int
  • 採用stdcall調用約定
  • 注意到一個void*論據。

所以我的建議是「給它一個功能,它的要求籤名」。

class Blah 
{ 
    static unsigned int __stdcall Start(void*); 
}; 
+7

+1教人閱讀! – xtofl 2009-08-11 12:43:56

+0

謝謝,但我不熟悉func指針:) lemme試試你的解決方案 – akif 2009-08-11 15:42:18

+1

然後這可能會幫助你一些: 函數指針教程 - http://www.newty.de/fpt/index.html – TheUndeadFish 2009-08-11 23:01:26

1
class Blah 
{ 
    static unsigned int __stdcall Start(void *); 
}; 
+0

爲什麼unsigned int?我沒有從線程中返回任何東西。即使我不得不返回一些我應該返回的內容 – akif 2009-08-11 11:42:09

+0

你有int main()的原因相同:因爲你的線程應該返回一些設計。只要返回0,如果你沒有更好的東西。 – MSalters 2009-08-11 11:44:11

+0

不能正常工作 class Blah static void unsigned int __stdcall Start(); }; unsigned int類型胡說::開始(){} 現在這個錯誤 :錯誤C2664: '_beginthreadex':不能從轉換參數3 'unsigned int類型(無效)' 到「無符號整型(__stdcall *)(無效* )' – akif 2009-08-11 11:53:35

3
class Blah 
{ 
    static unsigned int __stdcall Start(void*); // void* should be here, because _beginthreadex requires it. 
}; 

傳遞到_beginthreadex的程序必須使用__stdcall調用約定和必須返回一個線程退出代碼

胡說的實施::開始:

unsigned int __stdcall Blah::Start(void*) 
{ 
    // ... some code 

    return 0; // some exit code. 0 will be OK. 
} 

在後面的代碼,你可以寫任何的以下內容:

hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); 
// or 
hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL); 

在第一種情況下Function-to-pointer conversion將根據C++標準4.3應用/ 1。在第二種情況下,您將隱式地將指針傳遞給函數。

+0

不錯的一個!特別是我不知道的函數到指針的轉換。 +1 – xtofl 2009-08-11 12:46:49

2
class Blah 
{ 
    public: 
    static DWORD WINAPI Start(void * args); 
}; 
+1

缺少作爲預期簽名一部分的'void *'參數。 – jalf 2009-08-11 12:38:16

+1

謝謝 - 可悲的是,這是從工作代碼複製(不正確) - 也許我越來越老: - ( – 2009-08-11 12:46:55

+0

當你無論如何與Windows定義,使用LPVOID arg :) – 2009-11-06 06:27:01

2

以下是編譯的版本:

class CBlah 
{ 
public: 
    static unsigned int WINAPI Start(void*) 
    { 
    return 0; 
    } 
}; 

int main() 
{ 
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL); 

    return 0; 
} 

需要以下變化:

(1)。 Start()函數應該返回unsigned int

(2)。它應該採用void *作爲參數。

編輯

刪除點(3)根據註釋

+1

對於靜態功能'函數到指針的轉換'將被應用。 (3)中沒有必要。 – 2009-08-11 12:34:58