Re: Casting function pointers
- From: "andrew queisser" <andrew.queisser@xxxxxx>
- Date: Wed, 30 Jan 2008 13:20:47 -0800
"KKL" <kishore.luthra@xxxxxxxxx> wrote in message
news:ec127657-7ed8-41ac-b951-cf974e627cf3@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[example casting various member functions to task functions snipped]
1) You have to pass a compatible function pointer to the "TaskCreate"
function. Frequently this will be "void TaskType(void *arg)" or something
like "int TaskType(void *arg)". Some OSes might have additional parameters
but generally void * is enough. You generally can't cast a function pointer
to a different one, especially if the argument list is different, since the
stack will probably get misaligned or the arguemnts will get passed in the
wrong registers.
2) Member functions in C++ take the hidden "this" point argument so you can
never pass them to general "TaskCreate" type functions unless the OS knows
about the base class of your class.
What I usually do is this:
class ActiveClass
{
protected:
static void ThreadStarter(void *arg) { ((ActiveClass
*)arg)->ThreadProc(); }
void ThreadProc()
{
while (1)
{
DoTaskStuff();
}
}
public:
int Start() { TaskCreate(ThreadStarter, this); } // assumption: second
argument is what's passed to "arg"
};
The important thing is that ThreadStarter is static, which turns it into a
normal non-member function and that arg is cast to the type of the class
that has the member function with the task handling.
There are various ways of generalizing this approach with templates. You can
also pull out the ThreadStarter into a function outside of the class but I
like bundling things together as shown.
Andrew
.
- References:
- Casting function pointers
- From: KKL
- Casting function pointers
- Prev by Date: Re: searching embedded system
- Next by Date: Re: C programming on ARM
- Previous by thread: Re: Casting function pointers
- Next by thread: Re: Casting function pointers
- Index(es):
Relevant Pages
|