"Bill Cunningham" <so**@some.net> wrote in message
How can C be used to created a "Vtable" like C++'s virtual functions? > I
bet this involves struct.
typedef struct
{
void (*pt)(void *ptr, double t, double *x, double *y);
double (*len)(void *ptr);
void *ptr;
}LINEINTERFACE;
This is an interface for a 2D line. There are two functions, one to get the
x, y position for a point t (0-1) along the length, the other to get the
length of the line.
Now lets define two lines
typedef struct
{
double x1;
double y1;
double x2;
double y2;
} STRAIGHT;
typedef struct
{
double x[4];
double y[4];
} BEZIER;
Now you can write functions
void getpoint(void *straight, double t, double *x, double *y)
{
STRAIGHT *line = straight;
*x = line->x1 + t * (line->x2 - line->x1);
*y = line->y1 + t * (line->y2 - line->y1);
}
And so on.
You the set up your LINEINTERFACES with these function pointers, plus a
pointer to the line data (either a bezier or a striaght line).
Now we have a client function
void movespaceship(LINEINTERFACE *path)
{
double len;
double t;
double x;
double y;
len = path->len(path->ptr);
for(t=0;t<=1;t += 1/len)
{
path->pt(path->ptr, t, &x, &y);
displayshipat(x,y);
dorestofprogram();
}
}
Note that we can now add any type of line to this function, as long as we
can calculate a length and a point t. The ship could go in a spiral, or a
zigzag, or anything else.