Pass a class as argument to a NSThread

122 Views Asked by At

How can I pass a class as argument to a thread using NSThread. In windows I was doing something like:

DWORD WINAPI threadFunc(LPVOID mpThis) {
    MYCLSS *pThis = reinterpret_cast<MYCLSS*>(mpThis);
  ....

void MYCLSS::func() {
  CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadFunc, (void*)this, 0, NULL);
  ....

For Mac I have not found any examples of this kind. Please help me

1

There are 1 best solutions below

6
Junayd Finley On

I found the solution, it can be like windows

class CLS_CPP {
public:
  void Func();
  void Check();
  int var_check;
};

@interface CLS_OSX : NSObject {
@public
  void *obj;
}
-(void)osx_thread;
@end
@implementation CLS_OSX
-(void)osx_thread {  
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    CLS_CPP *pThis = reinterpret_cast<CLS_CPP*>(obj);
  pThis->Check();
  NSLog(@"Check var %d", pThis->var_check);
  [NSThread exit];
  [pool drain];
}
@end

void CLS_CPP::Func() {
  var_check=77;
  CLS_OSX *trgt=[[CLS_OSX alloc] init]; 
  trgt->obj=(void*)this;
  [NSThread detachNewThreadSelector:@selector(osx_thread) toTarget:trgt withObject:trgt];
}
void CLS_CPP::Check() {
  NSLog(@"CLS_CPP::Check success");
}

int main(int argc, char ** argv) {
     
  CLS_CPP oAPP;
  oAPP.Func();  
    
}