Feb 25, 2010

Using a C++ Member Function in OSTaskCreate()

The NetBurner family of products uses the MicroC/OS real time operating system. In that RTOS you create new tasks with the OSTaskCreate() (or OSTaskCreateExt() ). The first parameter to this call is declared as void (*task)(void *pd), meaning it takes a pointer to a function that returns a void and takes a pointer to void as the only parameter. This is meant to be the function you use to kick off the processing for that task. Often it's an event loop of some sort. Since the parameter takes a function pointer you can’t pass a pointer to member function. You can however use the second parameter which is a  void* to pass in a pointer to the instance of the class that has the member function you want to invoke. This is all much clearer with a code snippet example:
   1: //Call this Class member function instead of directly calling OSTaskCreate
   2: void SomeTask::StartupTask()
   3: {
   4:     OSTaskCreate(InitializeWrapper, this, (void*) &TaskStack[STACK_SIZE], (void*) TaskStack, _taskPriority);
   5: }
   7: //Wrap what would have been your old static or C function in this method
   8: void SomeTask::InitializeWrapper(void* const pTaskObject)
   9: {
  10:     static_cast<SomeTask*> (pTaskObject)->Initialize(0);
  11: }
  13: //This is the method that was originally passed directly when
  14: //it was a C function or a static method.
  15: void SomeTask::Initialize(const void * const pd)
  16: {
  17: //In here you do all the things you want this task to do.
  18: }

You would now use this class to start a new task as follows:

   1: void UserMain(void * pd)
   2: {
3: //Get an instance of your class however you like. I typically want all my tasks
   4:     //as singletons.
   5:      SomeTask my_task = ServiceProvider::GetSomeTaskAsSingleton();
   6:      my_task.StartupTask();
   7: }

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.