c++ - How to call callback in member function thread? -


i'am writing small class rs232 port. can sync write , async read. so, async read i'm using second thread, waiting input data. when data received, want call user callback (that constructor argument) input data. it's like:

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

my problem is: readerthread must static pass pointer _beginthreadex() function. , in readerthread want call "datareceivedcallback", obtained user in constructor. can't, cause can't call non-static functions in static readerthread. also, can't make "datareceivedcallback" static, cause may have many instances of class (for com1, com2, com3) , every instance should have it's own callback, obtained user.

where architecture mistake? how implement it?

thanks in advance!

p.s. using visual studio 2005.

you need pass argument thread function (which have void *data available for).

now, add private element in class rs232:

class rs232 {       rs232(string portname, receivedcallback datareceived);     ~rs232();  private:     receivedcallback datareceivedcallback;  private:     static unsigned readerthread(void* data);  public:     senddata(string data); } 

and in constructor:

rs232::rs232(string portname, receivedcallback datareceived) {    ... various stuff initialize serial port ...     _beginthreadex(securityarg, stacksize, readerthread, this, ...) } 

and in readerthread function:

unsigned rs232::readerthread(void *data) {    rs232 *self = static_cast<rs232*>(data);     .... stuff read serial port ...      ... call callback:    self->datareceivedcallback(str);     ....  } 

Comments