5/12/2006

Objects and Firmware - Polymorphism

I mentioned earlier that the constraints of object based programming can be overcome in C in order to do full OO programming. This time I will review the simple polymorphing technique in C. This is of course extremely simplified example, but polymorphism in C can be done with function pointers. The example below defines a class called worker which has only one method (function) called doTheJob. We create two entities of worker, but define different implementation for doTheJob. The implementation is selected with the constructor and stored as a function pointer theJob.

***** worker.h *****

typedef struct worker
{
void (*theJob)( void );
} _worker;

extern void WORKER_construct( BYTE meIndex,
void (*function)( void ) ) ;
extern void WORKER_doTheJob( BYTE meIndex );
extern void setPORTA( void );
extern void clearPORTA( void );

***** worker.c *****

#include "uc_defs.h"
#include "worker.h"

worker theWorker[2];
#define me theWorker[meIndex]

void WORKER_construct( BYTE meIndex,
void (*function)(void) )
{
me.theJob = function;
}

void WORKER_doTheJob( BYTE meIndex )
{
me.theJob();
}

void setPORTA( void )
{
PORTA = 0xFF;
}

void clearPORTA( void )
{
PORTA = 0x00;
}

***** main.c *****

#include "uc_defs.h"
#include "worker.h"

void main( void )
{
WORKER_construct(0, &clearPORTA );
WORKER_construct(1, &setPORTA );

while( 1 )
{
if( PORTB & 0x01 )
{
WORKER_doTheJob(0); // executes clearPORTA
}
else
{
WORKER_doTheJob(1); // executes setPORTA
}
}
}

I use the WORKER_doTheJob -function to wrap the function pointer in order to keep the interface consistent. I know this adds unnecessary overhead, but hey, we are all artists here and in my opinion it looks more clear.

I have started some series of posts, but not been able to finish any of them. Good news, I will soon use this post as a starting point to finish the TDD hassle -series... :-)

If you got interested in Object-Oriented C Programming (OOCP), here's my tips for a starting point (online):
Evanthelix OO C page
Axel-Tobias Schreiner has done a great job in this book

No comments: