我正在为RS232端口编写小类。它可以同步写入和异步读取。所以,对于异步读取,我使用第二个线程,即等待输入数据。当收到数据时,我想用输入数据调用用户回调函数(也就是构造函数的参数)。它看起来像:如何在成员函数线程中调用回调函数?
typedef int (*ReceivedCallback)(string data);
class RS232
{
RS232(string portName, ReceivedCallback dataReceived);
~RS232();
private:
ReceivedCallback dataReceivedCallback;
private:
static unsigned ReaderThread(void* data);
public:
SendData(string data);
}
我的问题是:ReaderThread必须是静态传递指针,它_beginthreadex()函数。在ReaderThread中,我想调用“dataReceivedCallback”,从用户在构造函数中获取。但我不能,因为我不能在静态ReaderThread中调用非静态函数。此外,我不能让“dataReceivedCallback”静态,因为我可能有很多我的类的实例(对于COM1,COM2,COM3),每个实例都应该有它自己的回调,由用户获得。
我的架构错误在哪里?你将如何实现它?
在此先感谢!
P.S.使用Visual Studio 2005.
如果C++ 11是可能的话,则可以用成员函数启动std :: thread。请参阅http://stackoverflow.com/questions/10673585/start-thread-with-member-function – stefaanv