Issues with passing this as argument to AsyncTask

Hello,

I need to access the “this” pointer in an AsyncTask. In order to do so, I tried to implement the first solution described here Non-static AsyncTask.
Unfortunately I have an issue with one of the instance variable which is initialized to nullptr in the constructor but, if I try to access it using the pointer passed to the task, I get a non-null pointer:

THE CONSTRUCTOR
//...
    this->currFocus=nullptr;//the variable I m trying to access from the task

    AsyncTaskManager *task_mgr = AsyncTaskManager::get_global_ptr();
    PT(GenericAsyncTask) task;
    task = new GenericAsyncTask("cameraTask", &cameraTask, this);
    task_mgr->add(task);
//...
//THE TASK
AsyncTask::DoneStatus MyClass::cameraTask(GenericAsyncTask *task, void *data) {

    //Here I try to use the technique described in the other thread
    MyClass * cs = (MyClass*)data;

    /*here, I expect the following command to print "0" but it prints
      a valid memory address*/
    std::cout << cs->getCurrFocus() << std::endl;

    return AsyncTask::DS_cont;
}

for instance, the method getCurrFocus is just a plain getter:

NodePathWrapper * MyClass::getCurrFocus(){
  return this->currFocus;
}

am I missing something? :smiley:

It’s not clear from your code. Are you sure that the class actually outlives the task and doesn’t get destroyed (and the memory reused) before the task gets a chance to run?