您的位置:首页 > Web前端

CString转换成const char*的一种有效方法

2012-04-04 15:11 246 查看
在Visual Studio 200X下,CString直接转换成const char* 有点困难,下面是自己用的一种可行方案:

//得到目录路径

CString mPath=dlg.GetPathName();

//将目录路径转换成绝对路径以便cvLoadImage调用

int m=mPath.GetLength();

for(int index=0;index<m;index++)

{
   if(mPath.GetAt(index)=='\\')
{
 mPath.Insert(index,'\\');
 index++;
}
}

//将CString转换成LPCTSTR
LPCTSTR p=mPath.GetBuffer();

/*

将LPCTSTR转换为const char *,因为Unicode的问题,LPCTSTR1、在非UNICODE环境下为 const char * 2、在UNICODE环境下为
const unsigned short *

在情况2时需要借助API函数WideCharToMultiByte

int WideCharToMultiByte(
UINT CodePage,            // code page
DWORD dwFlags,            // performance and mapping flags
LPCWSTR lpWideCharStr,    // wide-character string
int cchWideChar,          // number of chars in string
LPSTR lpMultiByteStr,     // buffer for new string
int cbMultiByte,          // size of buffer
LPCSTR lpDefaultChar,     // default for unmappable chars
LPBOOL lpUsedDefaultChar  // set when default char used
);


*/

DWORD dwMinSize;

dwMinSize=WideCharToMultiByte(CP_ACP,NULL,p,-1,NULL,0,NULL,FALSE);

char * pp=new char[dwMinSize];

WideCharToMultiByte(CP_OEMCP,NULL,p,-1,pp,dwMinSize,NULL,FALSE);

//读取图像

IplImage* ip1=cvLoadImage(pp,-1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息