2021-07-20

c实现面向接口的demo

  1. c语言作为一门底层语言,跟嵌入式程序挂钩,在一定条件下,与shell等解决计算机里底层的问题,与现有的高级程序相比,缺乏灵活性,但更为适用,运行更加快捷。话不多说,直接上代码。
#include<stdio.h>
#include<stdlib.h>
struct Interface{
	int(*Initial)(void* handle);
	int(*Send)(void* handle,char * buff,int count);
	int(*Recv)(void* handle,char * buff);
	int(*Destory)(void* handle);	
};


typedef struct _tag_protocolTypel{
	struct Interface bi;
	char* CommTypeName;
}protocolTypel;


int protocol_Initial(void* handle){
	protocolTypel* p=(protocolTypel*)handle;
	p->CommTypeName = "protocolTypel";//可以通过公共接口传参访问原对象的所有成员(注册组啥的)
	printf("%s Initial\n",p->CommTypeName); 
}


int protocol_Send(void* handle,char * buff,int count){
	protocolTypel* p=(protocolTypel*)handle;
	printf("%s Send\n",p->CommTypeName);
}

int protocol_Recv(void* handle,char *buff){
	protocolTypel* p =(protocolTypel*) handle;
	printf("%s Recv\n",p->CommTypeName);
}

int protocol_Destory(void* handle){
	protocolTypel* p=(protocolTypel*)handle;
	printf("%s Destory\n",p->CommTypeName);
}

int Initial(struct Interface *pInterface,int type){
	pInterface->Initial=protocol_Initial;
	pInterface->Send = protocol_Send;
	pInterface->Recv =protocol_Recv;
	pInterface->Destory =protocol_Destory; 
}

int Process(struct Interface *pInterface){
	pInterface->Initial(pInterface);
	pInterface->Send(pInterface,NULL,0);
	pInterface->Recv(pInterface,NULL);
	pInterface->Destory(pInterface); 
}

int main(int argc,char *argv[]){
	protocolTypel protocol;
	Initial((struct Interface*)&protocol,1);
	Process((struct Interface*)&protocol);
	return 0;
}

作为通用型指针,在计算机里,不管哪个语言都有指针,在c和c++的格式规范下,传参也成为了必要性,这个demo仅限于学习,模拟了初始生成信息包,以及发送生成包,以及接受信息包,以及解析包的一个简单过程。
以此为分析,ping一下百度服务器,就可以看到了这个demo发送信息包以及接受等流程了
在这里插入图片描述

此处又是别的知识了,三次握手啥的。跳过不讲,此处申明一下,代码来源于公众号最后一个bug。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值