MFC字符编码

刚开始开始MFC程序的时候就遇到字符编码的问题,不知道可以设置工作默认编码,搜了下又发现默认的unicode编码又是什么utf_16,我勒个去,索性还是用的MBCS,向外面发送的时候再改用utf8编码,所用的方法如下:

char * CharConvert::zhToUtf8(CString str){
int len;
len = MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
wflag = TRUE;
wbuf = new WCHAR[len+1];//(WCHAR *)malloc(sizeof(WCHAR)*(len+1));
MultiByteToWideChar(CP_ACP,0,str,-1,wbuf,len);
str.Format("len is : %d",len);
len = WideCharToMultiByte(CP_UTF8,0,wbuf,-1,NULL,0,0,0);
flag = TRUE;
buf = new char[len+1];
WideCharToMultiByte(CP_UTF8,0,wbuf,-1,(LPSTR)buf,len,0,0);
return buf;
};
char * CharConvert::utf8ToZh(const char * p){
int len;
len = MultiByteToWideChar(CP_UTF8, 0, p, -1, NULL, 0);
wflag = TRUE;
wbuf = new WCHAR[len+1];
MultiByteToWideChar(CP_UTF8, 0, p, -1, wbuf, len);
len = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, NULL, 0, 0, 0);
flag = TRUE;
buf = new char[len+1];
WideCharToMultiByte(CP_ACP, 0, wbuf, -1, (LPSTR)buf, len, 0, 0);
return buf;
}
void CharConvert::destruct(){
if(wflag){
delete [] wbuf;//free(wbuf);
wflag = FALSE;
}
if(flag){
delete [] buf;
flag = FALSE;
}
};

而且在将转换后的字符串指针赋值的时候 ,一定要用String接收,再destruct,若用指针接收,则destruct之后原来的指针便指向无效内容了。

总之,一切都需要细心,否则会浪费很多时间。

posted @ 2013-01-09 15:48  jefffyang  阅读(2206)  评论(0编辑  收藏  举报