CodingConv.h
/**
* \file CodingConv.h
* \brief 编码格式转换接口定义文件
*/
#pragma once
/**
* \class CCodingConv CodingConv.h
* \brief 本地编码类型与UTF8编码类型转换封装类,用于sqlite中的编码类型转换
* \date 2010-6-8 9:31
*/
class CCodingConv
{
public:
/**
* \brief 将本地编码类型转换为UTF8编码类型
* \param[in] strIn 本地编码类型的字符串
* \param[out] strOutUTF8MB 转换后的UTF8编码格式的字符串
* \return 转换后的字符串长度
* \attention 本地函数为strOutUTF8MB申请的内存要在外部释放
*/
static size_t ConvertStringToUTF8( LPCTSTR strIn, char *& strOutUTF8MB );
/**
* \brief 将UTF8编码类型转换为本地编码类型
* \param[in] strInUTF8MB UTF8编码类型的字符串
* \param[in] len strInUTF8MB字符串的长度
* \param[out] strOut 转换后的本地编码格式的字符串
* \return NONE
*/
static void ConvertUTF8ToString( char * strInUTF8MB, size_t len, LPTSTR & strOut );
};
CodingConv.cpp
/**
* \file CodingConv.cpp
* \brief 编码格式转换接口实现文件
*/
#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
#include "CodingConv.h"
void CCodingConv::ConvertUTF8ToString( char * strInUTF8MB, size_t len, LPTSTR & strOut )
{
strOut=new TCHAR[len];
strOut[0]=0;
#ifdef UNICODE
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, strOut, (int)len);
#else
WCHAR * wChar=new WCHAR[len];
wChar[0]=0;
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, wChar, (int)len);
WideCharToMultiByte(CP_ACP, 0, wChar, (int)len, strOut, (int)len, 0, 0);
delete [] wChar;
#endif
}
size_t CCodingConv::ConvertStringToUTF8( LPCTSTR strIn, char *& strOutUTF8MB )
{
size_t len=_tcslen(strIn);
#ifdef UNICODE
int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, strIn, -1, 0, 0, 0, 0);
strOutUTF8MB=new char[iRequiredSize];
strOutUTF8MB[0]=0;
WideCharToMultiByte(CP_UTF8, 0, strIn, -1, strOutUTF8MB, iRequiredSize, 0, 0);
#else
WCHAR * wChar=new WCHAR[len+1];
wChar[0]=0;
MultiByteToWideChar(CP_ACP, 0, strIn, (int)len+1, wChar, (int)len+1);
int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, 0, 0, 0, 0);
strOutUTF8MB=new char[iRequiredSize];
strOutUTF8MB[0]=0;
WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, strOutUTF8MB, iRequiredSize, 0, 0);
delete [] wChar;
#endif
return iRequiredSize;
}