欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

C语言——把结构体数据封装成TLV格式的数据

发布时间:2025/10/17 编程问答 17 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C语言——把结构体数据封装成TLV格式的数据 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

功能描述:

typedef struct
{
    unsigned char ucPort;
    pid_t stPid;
}TEST_INFO_S;

结构体TETS_INFO_S内有两个变量分别是ucPort和stPid,在本文中把此结构体作为TLV的value部分,type部分为0,len为此结构体的大小。

代码实现:

#include <stdio.h> #include <string.h> #include <stdlib.h>#define TEST_TYPE 0 typedef struct {unsigned char ucPort;pid_t stPid; }TEST_INFO_S;typedef struct {unsigned int uiType;unsigned int uiLen; }TLV_HEAD_S;/* 简述:封装tlv结构体* 参数:unsigned int uiType 封住tlv结构体中的type字段* void *pvData 要封装的数据* unsigned int uiLen 要封装的数据长度* 返回值:成功后返回封装后结构体的地址,失败返回NULL* 备注:封装后的结构体空间使用完后需要释放* */ void * tlv_encap(unsigned int uiType, void *pvData, unsigned int uiLen) {void *pvTlv = NULL;TLV_HEAD_S *pstTlvHead = NULL;unsigned int uiDataLen = sizeof(TEST_INFO_S) + uiLen;pvTlv = calloc(1, uiDataLen);if(NULL == pvTlv){return NULL;}pstTlvHead = (TLV_HEAD_S *)pvTlv;pstTlvHead->uiType = uiType;pstTlvHead->uiLen = uiLen;memcpy(pvTlv + sizeof(TLV_HEAD_S), pvData, uiLen);return pvTlv; }int main() {TEST_INFO_S stTest = {0};void *pvTlvRes = NULL;stTest.ucPort = 55;stTest.stPid = 33;pvTlvRes = tlv_encap(TEST_TYPE, &stTest, sizeof(stTest));if(NULL == pvTlvRes){return -1;}TLV_HEAD_S *pstTlvHead = NULL;pstTlvHead = (TLV_HEAD_S *)pvTlvRes;printf("%d\n",pstTlvHead->uiType); printf("%d\n",pstTlvHead->uiLen); TEST_INFO_S *pstTest = {0};pstTest = (TEST_INFO_S *)(pvTlvRes + sizeof(TLV_HEAD_S));printf("%d\n",pstTest->ucPort); printf("%d\n",pstTest->stPid); return 0; }

显示结果:

[root@localhost tlv]# ./tlv 0 8 55 33

 

总结

以上是生活随笔为你收集整理的C语言——把结构体数据封装成TLV格式的数据的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。