print.h
#ifndef __PRINT_H__
#define __PRINT_H__
typedef void (*print_fn) (void *print_info, char *str);
struct print_info
{
print_fn print;
};
#endif
bird.c
#include "bird.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void bird_fly(struct bird *xBird)
{
printf("bird %s fly\r\n",xBird->name);
}
void print_bird(struct bird *xBird, char *str) {
printf("bird name=%s,str = %s\r\n", xBird->name,str);
}
static const struct print_info print_interface = {
.print = (print_fn)print_bird,
};
struct bird * init_bird(char *name)
{
struct bird *bird = malloc(sizeof(struct bird));
bird->name = name;
bird->interface = &print_interface;
bird->fly = (bird_fly_fn)bird_fly;
return bird;
}
void free_bird(struct bird *xBird)
{
free(xBird);
}
bird.h
#ifndef __BIRD_H__
#define __BIRD_H__
#include "print.h"
typedef void (*bird_fly_fn)(void);
struct bird {
const struct print_info *interface;
bird_fly_fn fly;
char *name;
};
struct bird * init_bird(char *name);
void free_bird(struct bird *xBird);
#endif
dog.c
#include <stdio.h>
#include "dog.h"
#include <string.h>
#include <stdlib.h>
void run_dog(struct dog *xDog) {
printf("dog %s run\r\n",xDog->name);
}
void print_dog(struct dog *xDog, char *str) {
printf("dog name=%s,str = %s\r\n", xDog->name,str);
}
static const struct print_info print_interface= {
.print = (print_fn)print_dog,
};
struct dog * init_dog(char *name) {
struct dog *xDog = malloc(sizeof(struct dog));
xDog->name = name;
xDog->interface = &print_interface;
xDog->run = (dog_run_fn)run_dog;
return xDog;
}
void free_dog(struct dog *xDog) {
free(xDog);
}
dog.h
#ifndef __DOG_H__
#define __DOG_H__
#include "print.h"
typedef void (*dog_run_fn) (void *dog);
struct dog {
const struct print_info *interface;
dog_run_fn run;
char *name;
};
struct dog * init_dog(char *name);
void free_dog(struct dog *xDog);
#endif
main.c
#include <stdio.h>
#include <stdlib.h>
#include "dog.h"
#include "bird.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
struct dog *dog1;
struct bird *bird1;
struct print_info **p;
dog1 = init_dog("Keji");
p = (struct print_info **)dog1;
(*p)->print(dog1,"dog1");
bird1 = init_bird("King");
p = (struct print_info **)bird1;
(*p)->print(bird1,"bird1");
free_dog(dog1);
free_bird(bird1);
return 0;
}