如何将对象传递给CreateThread函数?

时间:2011-07-06 23:55:06

标签: c++ winapi

我想将一个类的对象作为参数传递给CreateThread函数。

main

中以这种方式创建对象
Connection *connection = new Bluetooth();
Brick *nxt = new Brick(connection);

我传递给CreateThread的函数是:

DWORD WINAPI recieveFunct(Brick nxt)

最后,在CreateThread中调用main

IDRecieveThread = CreateThread(NULL, 0, recieveFunct, *nxt, 0, NULL);

main中,我创建了nxt个对象。该对象具有我想从线程调用的读写函数。但是,我无法让它发挥作用。

我是否需要它将对象强制转换为HANDLE?或者我看起来完全错了?


感谢您的反馈!

我已经实现了上面给出的解决方案:

int main()
{
  HANDLE IDRecieveThread = 0;

  //set up the NXT
 Connection *connection = new Bluetooth(); Brick *nxt = new Brick(connection);


  //Setup connection
  cout << "connecting..." << endl;
  connection->connect(3);
  cout << "connected" << endl;

  cout << "Starting recieve thread...." << endl;
  IDRecieveThread = CreateThread(NULL, 0, recieveFunct, reinterpret_cast<void*>(nxt),  0, NULL);
  cout << "Recieve thread started" << endl;
}

但是编译器给出了这个错误:

C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp||In function `int main()':|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp|39|error: invalid conversion from `void (*)(void*)' to `DWORD (*)(void*)'|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp|39|error:   initializing argument 3 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\recievethread.h|4|warning: 'void recieveFunct(void*)' declared `static' but never defined|
||=== Build finished: 2 errors, 1 warnings ===|

有人能告诉我什么是错的吗?我在调用CreateThread函数时收到错误。

2 个答案:

答案 0 :(得分:4)

您需要将nxt投放到LPVOID,而不是HANDLE。 MSDN说“LPVOID lpParameter [in,optional] - 指向要传递给线程的变量的指针。”用于将数据传递到回调函数或线程的这种设计模式通常称为“用户数据”指针。

http://msdn.microsoft.com/en-us/library/ms682453%28v=vs.85%29.aspx

当你调用LPVOID并在你的CreateThread()线程函数中取消它时,你可以将你的Brick指针转换为recieveFunct(即指向void的指针):

static void recieveFunct(void* pvBrick)
{
    Brick* brick = reinterpret_cast<Brick*>(pvBrick);
}

Connection *connection = new Bluetooth(); Brick *nxt = new Brick(connection);
IDRecieveThread = CreateThread(NULL, 0, recieveFunct, reinterpret_cast<void*>(nxt), 0, NULL);

另外,如果您使用的是MSVCRT库,则可以考虑使用beginthreadex()而不是CreateThread()beginthreadex()将确保为您的线程正确初始化MSVCRT。

答案 1 :(得分:2)

使用此签名:

DWORD WINAPI recieveFunct(void* pParam)
{
   Brick* pBrick = (Brick*)pParam; // Or whichever casting you prefer

  // Use the  `pBrick`

  return 0;
}

将线程创建为:

Brick *nxt = new Brick(connection);
CreateThread(NULL, 0, recieveFunct, (void*)nxt, 0, NULL);