OOPC学习1
最近在研究面向对象的方式进行嵌入式编程,发现了《UML+OOPC嵌入式C语言开发精讲》一书,书中提供的思路着实有用,特此作为学习记录;
将C语言封装成类,在开发的过程中直接可以面向对象的思想进行开发,这样结构清晰,易于联合开发与维护,下面将学习到的代码作为简单的分享与说明。
首先宏定义式的封装,如下程序Lwoopc.h:
#ifndef __LOOPC_H__
#define __LOOPC_H__
#include "malloc.h"
#define CLASS(type)\
typedef struct type type;\
struct type
#define CTOR(type)\
void* type##New()\
{\
struct type *t;\
t = (struct type*)malloc(sizeof(struct type));
#define CTOR2(type, type2) \
void* type2##New() \
{ \
struct type *t; \
t = (struct type *)malloc(sizeof(struct type));
#define END_CTOR return (void*)t; }
#define FUNCTION_SETTING(f1,f2) t->f1 = f2;
#define IMPLEMENTS(type) struct type type
#define INTERFACE(type) struct type \
typedef struct type type; \
struct type
#endif
说明:首先定义CLASS宏定义,其实就是进行结构体定义,如
CLASS(A)
{
int a;
int b;
.
.
.
};
经过宏替换后为
typedef struct A A;
struct A
{
int a;
int b;
.
.
.
};
CTOR为构造器的意思,就是C++中的构造函数, CTOR(A)宏替换后如下:
void* ANew()
{
struct A *t;
t = (struct A*)malloc(sizeof(struct A));
return (void*t);
}
下面在VC6上编写运行里程,程序如下:
cx12_lig.h:
#ifndef __LIGHT_H__
#define __LIGHT_H__
#include "Lw_oopc.h"
CLASS(Light)
{
int state;
void (*init)(void *);
int (*get_state)(void *);
void (* set_light)(void *,int flag);
};
#endif
cx12_lig.c:
#include <stdio.h>
#include <stdlib.h>
#include "cx12_lig.h"
static void init(void *t)
{
Light *cthis = (Light *)t;
cthis->state = 0;
}
static int get_state(void *t)
{
Light *cthis = (Light *)t;
return cthis->state;
}
static void set_light(void *t, int flag)
{
Light *cthis = (Light *)t;
cthis->state = flag;
if (cthis->state == 0)
printf("LIGHT_OFF!\n");
else
printf("LIGHT_ON!\n");
}
CTOR(Light)
FUNCTION_SETTING(init, init);
FUNCTION_SETTING(get_state, get_state);
FUNCTION_SETTING(set_light, set_light);
END_CTOR
cx12_sw.h:
#ifndef __SWITCH_H__
#define __SWITCH_H__
#include "Lw_oopc.h"
#include "cx12_lig.h"
CLASS(Switch)
{
int state;
Light *light_obj;
void (*init)(void*, Light*);
int (*get_state)(void *);
void (*set_switch)(void *);
};
#endif
cx12_sw.c:
#include <stdio.h>
#include <stdlib.h>
#include "cx12_sw.h"
static void init(void *t, Light* light)
{
Switch *cthis = (Switch *)t;
cthis->state = 0;
cthis->light_obj = light;
}
static int get_state(void * t)
{
Switch *cthis = (Switch *)t;
return cthis->state;
}
static void set_switch(void *t)
{
Switch *cthis = (Switch*)t;
int st;
Light* light;
cthis->state = !(cthis->state);
light = cthis->light_obj;
st = light->get_state(light);
if (st == 1)
light->set_light(light, 0);
else
light->set_light(light, 1);
}
CTOR(Switch)
FUNCTION_SETTING(init, init);
FUNCTION_SETTING(get_state, get_state);
FUNCTION_SETTING(set_switch, set_switch);
END_CTOR
main.c:
#include "cx12_lig.h"
#include "cx12_sw.h"
int main(void)
{
Light* light = (Light*)LightNew();
Switch* wall = (Switch*)SwitchNew();
Switch *door = (Switch*)SwitchNew();
light->init(light);
wall->init(wall,light);
door->init(door,light);
wall->set_switch(wall);
door->set_switch(door);
door->set_switch(door);
wall->set_switch(wall);
}
运行结果: