在Visual Studio 下,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
intWideCharToMultiByte(UINTCodePage,//codepageDWORDdwFlags,//performanceandmappingflagsLPCWSTRlpWideCharStr,//wide-characterstringintcchWideChar,//numberofcharsinstringLPSTRlpMultiByteStr,//bufferfornewstringintcbMultiByte,//sizeofbufferLPCSTRlpDefaultChar,//defaultforunmappablecharsLPBOOLlpUsedDefaultChar//setwhendefaultcharused);
int WideCharToMultiByte(UINT CodePage, // code pageDWORD dwFlags, // performance and mapping flagsLPCWSTR lpWideCharStr, // wide-character stringint cchWideChar,// number of chars in stringLPSTR lpMultiByteStr,// buffer for new stringint cbMultiByte,// size of bufferLPCSTR lpDefaultChar,// default for unmappable charsLPBOOL 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);