一个通用的C++结构定义如下:
typedef struct tagCommonStruct { long len; void* buff; }CommonStruct_st;
此接口对应的普通序列化、反序列化接口如下:
unsigned char* EncodeCommonStruct(const CommonStruct_st& CommonSt) { //分配内存 unsigned char* strBuff = (unsigned char*)malloc(CALC_COMMON_ST_LEN(&CommonSt)); if (NULL == strBuff) { return NULL; } //填充内容 *(long*)strBuff = CommonSt.len; if (CommonSt.len > 0) { memcpy(strBuff + sizeof(long), CommonSt.buff, CommonSt.len); } return strBuff; } BOOL DecodeCommonStruct(const unsigned char* strBuff, long len, CommonStruct_st& CommonSt) { long st_len; if (NULL == strBuff) { return FALSE; } //获取到当前长度 st_len = *(const long*)strBuff; //校验BUFF内容合法性 if (st_len + sizeof(long) > len) { return FALSE; } CommonSt.len = st_len; CommonSt.buff = (void*)malloc(st_len); memcpy(CommonSt.buff, strBuff + sizeof(long), st_len); return TRUE; } void EncodeCommonStruct_S(const CommonStruct_st& CommonSt, std::string& strOut) { //分配内存 strOut.resize(CALC_COMMON_ST_LEN(&CommonSt)); //填充内容 *(long*)&(strOut[0]) = CommonSt.len; if (CommonSt.len > 0) { memcpy(&(strOut[0]) + sizeof(long), CommonSt.buff, CommonSt.len); } return; } BOOL DecodeCommonStruct_S(const unsigned char* strBuff, long len, CommonStruct_st& pCommonSt, std::string& strInnBuff) { long st_len; if (NULL == strBuff) { return FALSE; } //获取到当前长度 st_len = *(const long*)strBuff; //校验BUFF内容合法性 if (st_len + sizeof(long) > len) { return FALSE; } pCommonSt.len = st_len; strInnBuff.resize(st_len); //pCommonSt.buff = (void*)malloc(st_len); pCommonSt.buff = &strInnBuff[0]; memcpy(pCommonSt.buff, strBuff + sizeof(long), st_len); return TRUE; }
支持批量操作的序列化、反序列化接口:
#define MAX_COMMON_STRUCT_PARAM_NUMBER (16) void EncodeCommonStructV(std::string& strOut, int nStNum, ...) { int index = 0; int nBufLen; unsigned char* strTemp; //最多允许16个 va_list arg_ptr; CommonStruct_st CommStructStArray[MAX_COMMON_STRUCT_PARAM_NUMBER]; // if (nStNum > MAX_COMMON_STRUCT_PARAM_NUMBER) { return; } //依次取出相应的结构、指针位置 nBufLen = 0; va_start(arg_ptr, nStNum); for(index = 0; index < nStNum; index ++){ CommStructStArray[index].len = va_arg(arg_ptr, int); CommStructStArray[index].buff = va_arg(arg_ptr, void*); nBufLen += CALC_COMMON_ST_LEN(&CommStructStArray[index]); } va_end(arg_ptr); //计算总字符长度 strOut.resize(nBufLen, '