Tuesday, December 06, 2016

dispatch table with function pointers in C simple sample

#include "stdio.h"
#include "string.h"

void foo() {
printf("in foo\n");
}
void bar() {
printf("in bar\n");
}
void foo2() {
printf("in foo2\n");
}
struct table_entry_s { char *name; void(*function)(); };

typedef struct table_entry_s table_t;

//populate the table
table_t dispatchTable[256] =
{ {"foo", foo}, {"bar", bar}, {"foo2", foo2}, {NULL, NULL} };

#define NUM_ENTRIES 3

void dispatchKernel(char *string)
{
int iFound = 0;

printf("dispatchKernel with %s\n", string);

for (int i = 0; i < NUM_ENTRIES; i++)
{
char *result = NULL;
result = strstr(string, dispatchTable[i].name);
if (result == NULL)
{
printf("%s was not in %s\n", dispatchTable[i].name, string);
}
else
{
iFound = 1;
printf("Found %s in %s\n", dispatchTable[i].name, string);
dispatchTable[i].function();
}
}
}

void main()
{
printf("hello\n");

printf("dispatchTable[0] name = %s\n", dispatchTable[0].name);
printf("dispatchTable[1] name = %s\n", dispatchTable[1].name);
printf("dispatchTable[2] name = %s\n", dispatchTable[2].name);

dispatchTable[0].function();
dispatchTable[1].function();
dispatchTable[2].function();

dispatchKernel("fdafsdbarfdsafs");

printf("goodbye\n");

}

No comments: