2009-08-11 162 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