当前位置:网站首页>Interface oriented programming in C language

Interface oriented programming in C language

2022-06-13 06:33:00 Road and distance

C Interface oriented programming of language

Create an interface

  • The header file
// hello_socket.h

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

typedef void (* initHandle)(void ** handle);
typedef void (* sendMessage)(void * handle,char * message,int length);
typedef void (* receiveMessage)(void * handle,char * message,int *length);
typedef void (* closeHandle)(void * handle);

void FrameWork(initHandle _init,sendMessage _send,receiveMessage _receive,closeHandle _close);
  • C file
// hello_socket.c

#include "hello_socket.h"

void FrameWork(initHandle _init, sendMessage _send, receiveMessage _receive, closeHandle _close) {
//  Initialize connection 
    void *handle = NULL;
    _init(&handle);
//  send data 
    char buff[] = "hello world";
    int length = strlen(buff);
    _send(handle,buff, length);
    printf(" send data  ---> %s\n length  ---> %d\n",buff,length);
//  receive data 
    char receiveBuff[1024] = {0};
    int receiveLength = 0;
    _receive(handle,receiveBuff, &receiveLength);
//  Close the connection 
    _close(handle);
    handle = NULL;

    printf(" receive data  ---> %s\n length  ---> %d\n",receiveBuff,receiveLength);
}

Implementation interface

  • The header file
// hello_socket_impl.h

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


void initHandleImpl(void ** handle);
void sendMessageImpl(void * handle,char * message,int length);
void receiveMessageImpl(void * handle,char * message,int *length);
void closeHandleImpl(void * handle);
  • C file
// hello_socket_impl.c

#include "hello_socket_impl.h"

struct Info{
    char data[1024];
    int length;
};

void initHandleImpl(void ** handle){
    struct Info *info = malloc(sizeof(struct Info));
    memset(info,0, sizeof(struct Info));
    *handle = info;
}
void sendMessageImpl(void * handle,char * message,int length){
    if(handle == NULL || message == NULL || length <= 0) return;
    struct Info *info =(struct Info *)handle;
    strncpy(info->data,message,length);
    info->length = length;

}
void receiveMessageImpl(void * handle,char * message,int *length){
    if(handle == NULL || message == NULL || length == NULL) return;
    struct Info *info =(struct Info *)handle;
    strncpy(message,info->data,info->length);
    *length = info->length;
}
void closeHandleImpl(void * handle){
    if(handle == NULL)
        return;
    free(handle);
    handle = NULL;
}

Test interface

#include "hello_socket.h"
#include "hello_socket_impl.h"

int main(){
	FrameWork(initHandleImpl,sendMessageImpl,receiveMessageImpl,closeHandleImpl);
    return 0;
}
原网站

版权声明
本文为[Road and distance]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270554450091.html