windows下字符集转换通常都用WideCharToMultiByte和MultiByteToWideChar。当然,也可以用来自运行时库的wcstombs()和mbstowcs()系列。
转换的步骤就那几步,也不复杂。但如果每次都重复一遍,也是件很无聊的事情。尤其是当项目里有多名人员参加,代码风格可能不统一,在对申请内存及失败的处理可能不一致,导致过不了代码审查。所以有必要封装一个字符转换的类。
//CharSet.h
#ifndef LIB_CHARSET_TRANLATE_H
#define LIB_CHARSET_TRANLATE_H
#pragma once
#include <windows.h>
class CCharSet
{
public:
CCharSet(void);
~CCharSet(void);
const wchar_t* MBCS2WCS(LPCSTR lpMultiByteStr , UINT CodePage, DWORD dwFlags);
const char* WCS2MBCS(LPCWSTR lpWideCharStr, UINT CodePage, DWORD dwFlags);
protected:
CCharSet(const CCharSet &);
CCharSet & operator = (const CCharSet &);
void* m_p;
void Clear(void);
};
#endif
//CharSet.cpp
#include "CharSet.h"
CCharSet::CCharSet(void):m_p(NULL)
{}
CCharSet::~CCharSet(void)
{
Clear();
}
const wchar_t* CCharSet::MBCS2WCS(LPCSTR lpMultiByteStr, UINT CodePage, DWORD dwFlags)
{
Clear();
int iLen = ::MultiByteToWideChar(CodePage,dwFlags,lpMultiByteStr,-1,NULL,0);
if (0 == iLen)
return NULL;
m_p = malloc((iLen+1)*2);
if (NULL == m_p)
return NULL;
memset(m_p,0,iLen+1);
::MultiByteToWideChar(CodePage,dwFlags,lpMultiByteStr,-1,(WCHAR*)m_p,iLen);
return (WCHAR*)m_p;
}
使用示例
#include "stdafx.h"
#include "CharSet.h"
#include <string>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR wcs[] = L"Hello world";
CCharSet charSet;
std::string str = charSet.WCS2MBCS(wcs,CP_ACP,0);
std::cout<<str<<std::endl;
char sz[] = "Hi, Charset.";
std::wstring wstr = charSet.MBCS2WCS(sz,CP_ACP,0);
std::wcout<<wstr<<std::endl;
return 0;
}