_beginthreadex静态成员函数

时间:2009-08-11 11:34:32

标签: c++ function static multithreading member

如何创建静态成员函数的线程例程

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 *)'***

我做错了什么?

5 个答案:

答案 0 :(得分: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*);
};

答案 1 :(得分:3)

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

传递给_beginthreadex的例程必须使用__stdcall调用约定,必须返回线程退出代码

Blah的实现::开始:

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);

在第一种情况下,将根据C ++标准4.3 / 1应用Function-to-pointer conversion。在第二种情况下,您将隐式地将指针传递给函数。

答案 2 :(得分:2)

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

答案 3 :(得分: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)

答案 4 :(得分:1)

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