Linux:C语言实现面向接口编程

文章介绍了面向接口编程的概念,将其与函数指针关联,并提供了一个示例,展示如何通过定义接口结构体和初始化函数来降低代码耦合。在示例中,`initial`函数用于设置接口函数指针,而`start`、`working`和`befree`是具体的接口实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面向接口编程不是什么新鲜玩意,说得直白点就是函数指针的使用,不过我觉得可以形成一种编程的思想来指导嵌入式程序设计,特别是对于降低代码的耦合还是比较奏效的。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int start(void * p);//接口函数,乙方实现具体的逻辑
int working(void * p);//接口函数,乙方实现具体的逻辑
int befree(void * p);//接口函数,乙方实现具体的逻辑
struct ApiFunc * initial (void * p,void * a, void * b, void * c, char * s); //初始化函数,甲方调用传入参数

//面向接口编程,先定义出接口
struct interface
{//包含三个接口函数
int (* start)(void );
int (
working)(void );
int (
befree)(void *);
};

//再定义出一个结构体用来传递参数
struct ApiFunc
{
struct interface inter1;
char name[20];
int a;
int b;
int c;
};

struct ApiFunc * initial(void * p,void * a, void * b, void * c, char * s)//初始化函数,接收甲方调用的参数并初始函数指针
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
Ap->a = *(int *)a;
Ap->b = *(int *)b;
Ap->c = *(int *)c;
strcpy(Ap->name,s);
printf(“%s\n”,Ap->name);
Ap->inter1.start = start;
Ap->inter1.working = working;
Ap->inter1.befree = befree;
return Ap;
}

int start(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;

printf("%d:%s %s\n",Ap->a,Ap->name,"start work");

return 0;

}

int working(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
printf(“%d:%s %s\n”,Ap->b,Ap->name,“is working”);
return 0;
}

int befree(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
printf(“%d:%s %s\n”,Ap->c,Ap->name,“is free!”);
return 0;
}

int main(int argc, const char * agrv[])
{
int a = 1;
int b = 2;
int c = 3;
char buf [20] = {“I am a worker”};
struct ApiFunc myapi;
struct ApiFunc * p = initial(&myapi,(void *)&a,(void *)&b,(void *)&c,buf);//调用initial函数初始化ApiFunc结构体
myapi.inter1.start§;
myapi.inter1.working§;
myapi.inter1.befree§;
}

结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值