收发信息设计 指针作输入输出

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

int handleIni(void **handle/*Out*/);
int socketSend(void *handle/*in*/, char *msg/*in*/, int len/*in*/);
int socketReci(void *handle/*in*/, char *msg/*out*/, int *len/*in*/);
void socketFree(void *handle/*in*/);

//定义结构体
typedef struct Socket_C
{
    char version[8];
    char *msg;
    int len;
}SC;

int handleIni(void **handle)
{
    int rv = 0;
    if (handle == NULL)
    {
        rv = -1;
        printf("fun handleIni error.");
        goto End;
    }
    SC *example = NULL;
    //分配内存
    example = (SC *)malloc(sizeof(SC));
    if (example == NULL)
    {
        rv = -2;
        printf("fun handleIni malloc error.");
        goto End;
    }
    //定义版本号
    memcpy(example->version, "1.11", 4);
    *handle = example;
End:
    return rv;
}

int socketSend(void *handle, char *msg, int len)
{
    int rv = 0;
    SC * s = NULL;
    char * p = NULL;
    if (handle == NULL || msg == NULL || len > 2048)
    {
        rv = -1;
        printf("fun socketSend param error.");
        goto End;
    }
    s = (SC *)handle;
    //分配内存
    p = (char *)malloc(len * sizeof(char));
    //复制字符串
    memcpy(p, msg, len);
    //设置长度
    s->len = len;
    //挂上指针
    s->msg = p;

End:
    return rv;
}

int socketReci(void *handle, char *msg, int *len)
{
    int rv = 0;
    SC * s = NULL;
    if (handle == NULL || msg == NULL || len == NULL)
    {
        rv = -1;
        printf("fun socketReci param error.");
        goto End;
    }
    s = (SC *)handle;
    //复制字符串
    memcpy(msg, s->msg, s->len);
    //修改字符长度
    *len = s->len;
End:
    return rv;
}

void socketFree(void *handle)
{
    SC * p = NULL;
    if (handle != NULL)
    {
        p = (SC *)handle;
        if (p->msg != NULL)
        {
            free(p->msg);
            p->msg = NULL;
        }
        free(p);
    }
}

void main()
{
    //句柄
    void *handle = NULL;
    //发送的信息
    char msgsend[] = "hellow world!";
    //接收的信息
    char msgreci[2048] = {0};
    //字符长度
    int len = 0;
    //初始化句柄
    handleIni(&handle);
    //发送信息
    socketSend(handle, msgsend, sizeof(msgsend));
    //接收信息
    socketReci(handle, msgreci, &len);
    //释放句柄
    socketFree(handle);
    //打印接收到的信息
    printf("%s
", msgreci);
    system("pause");
}
原文地址:https://www.cnblogs.com/godehi/p/8496886.html