Passing a pointer of a function TO a function?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Freaks,

I'm trying to make a function, that can accept a pointer to another function. This first function would then store the pointer and later execute the function - like a minature RTOS.

I can do it via a variable:

(void)(*TaskPtr)(void) = NameOfFunction1;

And later:

TaskPtr();

To execute. How would I do the same thing with a function parameter? Example (fragment):

struct MeleeTaskData
{
	void *SubPtr;
	char Timeout;
};

void TaskHandler_AddTask (void *TaskPtr, char Tout);
void TaskHandler_CheckTasks (int MsElapsed);
MeleeTaskData Tasks[30];
char TotalTasks;

void TaskHandler_AddTask (void *TaskPtr, char Tout)
{
	struct MeleeTaskData NewTask;

	NewTask.SubPtr = TaskPtr;
	NewTask.Timeout = Tout;

	Tasks[TotalTasks++] = NewTask;
}

void TaskHandler_CheckTasks (int MsElapsed)
{
	for (char CTask = 0; CTask = 29; CTask++)
	{
		if (Tasks[CTask].Timeout >= MsElapsed)
		{
			(void)(Tasks[CTask].SubPtr)(void);
			Task();
		}
	}
}

The compiler goes banannas at this. What's the correct way?
- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

It seems to me that I PMed you something a while back that used function pointers; it included passing function pointers as arguments to functions. You should be able to refer to it for inspiration on how to write your own task scheduler.

Try something like this: (Slight modifications to ensure sanity checks are in place. Funny things might happen otherwise.)

typedef void (*pt2func)(void);
struct MeleeTaskData
{
   pt2func SubPtr;
   uint8_t Timeout;
};

MeleeTaskData Tasks[30];
uint8_t TotalTasks;

void TaskHandler_AddTask(pt2func TaskPtr, uint8_t Tout)
{
   if(TotalTasks < 30)
   {
      Tasks[TotalTasks].SubPtr = TaskPtr;
      Tasks[TotalTasks++].Timeout = Tout;
   }
}

void TaskHandler_CheckTasks(uint16_t MsElapsed)
{
   for(uint8_t CTask = 0; CTask <= 29; CTask++)
   {
      if(Tasks[CTask.Timeout >= MsElapsed && Tasks[CTask].SubPtr != NULL)
         (*(Tasks[CTask].SubPtr)) (); // Maybe extra parantheses here...
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

(Hits head against wall while cursing). Thanks - it's always a dumb mistake with me, isn't it!

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

lfmorrison wrote:

...
void TaskHandler_CheckTasks(uint16_t MsElapsed)
{
   for(uint8_t CTask = 0; CTask <= 29; CTask++)
   {
      if(Tasks[CTask.Timeout >= MsElapsed && Tasks[CTask].SubPtr != NULL)
         Tasks[CTask].SubPtr(); // even less
   }
}


:wink:

Regards,