I write a lot of programs for embedded systems, and I prefer to program in C++ whenever possible. However, for some smaller processors, a C++ compiler either doesn't exist or else is expensive. Recently, I needed to port an existing C++ project to a processor for which I had only a C compiler. The project had benefited greatly from using an inheritable class structure, so I decided to try and develop a mechanism for building inheritable classes in C.

I am not the first to do this, of course, and others have published successful methods. Miro Samek, for instance, developed a set of macros that hide the C code and allow a C++-like syntax (see Practical State Charts in C/C++, by Miro Samek, CMP Books, 2002). Hekon Hallingstad's class implementation used the offsetof() macro to access parent class data. Dan Saks described using C abstract types as classes (see "Abstract Types Using C," by Dan Saks, Embedded Systems Programming, October 2003). However, I had developed my own standalone class software over the years and my recent work was able to extend this to support classes with single inheritance.

For want of a better name, I use the name of the header fileC_Classes. Where would you use inheritance in embedded systems? Think of manufacturers building a range of chemical process controllers. They all have the same liquid crystal display, analog interfaces, power supply, RS-232 and radio interface, and similar sets of buttons and switches. The software interface to this hardware is also going to be similar. In this article, I introduce inheritance by defining a set of base classes that have drivers for all this hardware and well defined interfaces. Thus, a range of instruments can use the same base class set and only need a set of derived classes that characterize the particular functionality and set of interfaces that a new instrument will use. This makes for straightforward instrument development.

A Simple Class Structure

C++ hides the class data structure within itself and provides strict rules for how it can be accessed. You don't have this luxury in C, but you can create something similar by defining a single structure to contain all the data belonging to the class.

For example, I use my C_Classes method to define a skeleton class that could be the basis for a motor controller. The class is Motor and it controls only the speed and direction. The microprocessor I am programming has a number of ports that are connected to a number of motor controller chips. To set a motor's speed, you need only write the direction and revolutions-per-minute (RPM) to its respective ports. To keep things simple, I just use integers.

The class data structure is defined in the Motor class header as a typedef :

typedef struct { int* mPort; int mSpeed; DIRECTION mDirection; } MotorData;

The MotorData structure is the definition template for the Motor class data. In C++, these variables would be declared in a private section of the class definition. The mPort class data variable is assigned the port address for a particular motor. This lets the same Motor class code manage several motors in the one application.

The DIRECTION type is a simple enum :

typedef enum { DR_UNKNOWN, DR_CCW, // counter-clockwise DR_CW, // clockwise } DIRECTION;

As in C++, the class has a constructor and a destructor. Creating an instance of the class is a call to the constructor using the statement:

MotorData* dMotor = MotorCtor(); </pre <P> <p>The constructor creates and initializes an instance of the <code>MotorData</code> structure just defined, then returns a pointer to it that is assigned to the <code>dMotor</code> class data pointer. Subsequently, the caller passes this pointer to the class at every method call. This is the technique the C++ compiler uses, only it does it under the covers. The class contains no instance data within itself: It just provides methods to manipulate the passed-in data.</p> <p>Okay, that looks simple enough, but how do you call a class method? </p> <p>Because I am developing a way to create inheritable classes, I need to be able to call methods in a base class through a derived class, add additional methods in that derived class, and override base class methods in the derived class if required. To do this, I build a table of function pointers in RAM that provides access to the public methods of the class. I create the definition of this table of vectors (or <code>vtable</code>) as another <code>typedef</code> that includes function pointer prototypes for each public method. In the <code>Motor</code> example, you need to be able to initialize the port address, and set/get the speed and direction, all via the class interface, so that makes five methods; see Example 1. <P> <p><b>Example 1: Initializing port address, and setting/getting speed and direction.</b><br> <pre class="brush: c; html: collapse;" style="font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; border: 1px dashed rgb(153, 153, 153); line-height: 14px; padding: 5px; overflow: auto; width: 100%;"> typedef struct { //--------------------------------------- // Set a copy of the port address to use. void (*InitPort)(MotorData*, int*); //--------------------------------------- // Set/Get the motor speed. void (*SetSpeed)(MotorData*, int); int (*GetSpeed)(MotorData*); //---------------------------------------- // Set/Get the motor rotation direction. void (*SetDirection)(MotorData*, DIRECTION); DIRECTION (*GetDirection)(MotorData*); } MOTOR;

Along with the vtable definition, the class header also includes the definition for a pointer to the vtable and prototypes for the constructor and destructor. These are all publicly accessible:

extern MOTOR* Motor; extern MotorData* MotorCtor(void); extern void MotorXtor(MotorData*);

Part of the constructor's job is to build in RAM the vtable containing the five function pointers and set the public class vtable pointer ( Motor ) to point to that location. After a call to the constructor, users of this class can call any of the public methods through the class pointer. For example, setting the motor speed to 450 RPM, and remembering you also need to pass in the class data pointer, would be the call:

Motor->SetSpeed(dMotor,450);

While the owner of the dMotor structure has no business ever looking inside it, after this call you would know that dMotor->mSpeed has a value equivalent to 450 RPM.

The Constructor

So how does the class constructor build the vtable and create the data instance?

Again, the header file contains a template of the vtable (the MOTOR typedef ). Within the class code file, an instance of this vtable is defined and this instance is copied from ROM to RAM. Continuing the example, in the Motor code file, the vtable instance along with the global class pointer declaration looks like Example 2 (a). It is crucial, of course, that the instance has the same order as the template. The constructor function looks like Example 2 (b).

Example 2: (a) vtable instance and global class pointer declaration; (b) constructor function.

(a)



static const MOTOR cMotor = { InitPort, SetSpeed, GetSpeed, SetDirection, GetDirection }; MOTOR* Motor;

(b)



MotorData* MotorCtor(void) { MotorData* d; // Create the data structure // and initialize the contents. d = Allocate(sizeof(MotorData)); d->mPort = NULL; d->mSpeed = 0; d->mDirection = DR_UNKNOWN; // Create the vtable by // copying it to RAM. if (InstCount++ == 0) { CREATE_VTABLE(Motor, cMotor, MOTOR); } return d; }

If there is a possibility that the class will have several instances, or be created and destroyed several times, then the class must ensure there is always only one vtable in RAM. To this end, every class has InstCount as a private variable that is used to keep track of the number of instances extant for this class. It is incremented during construction and decremented during destruction. The actual copying is conveniently done by the CREATE_VTABLE macro. This uses cMotor as a source, Motor as a destination, and the MOTOR structure size for both heap allocation and for the number of bytes to copy.

As an aside, my original C_Classes version for standalone classes used the simple Motor = & cMotor instead of the macro. You can still do this for standalone classes if RAM is in short supply.

Again, the constructor must also create and initialize the class data on the heap for every instantiation. To this end, the constructor creates a pointer that is returned to each individual caller to manage during the life of the class instance. The Allocate function is defined in the C_Classes header and is a simple wrapper around malloc that includes an internal allocation counter. The counter can be interrogated at any time and can be useful during debugging.