CString array and char *

hi, I saved the file names in a CString array.  and I need to pass these file names to a function "someFunc" which takes const char* .  but the code does not work.  the error says:

cannot convert parameter 1 from 'CString' to 'const char *'      

I also try to cast it into char* but failed too.

Any suggestions?
#define MAX_IMAGE_NUMBER 1000
CString fileName[MAX_IMAGE_NUMBER];
 
While()
{
.....
          fileName[i] = (LPCTSTR)finder.GetFilePath();
          someFunc((const char*)fileName[i]);
          i++;
......
}

Open in new window

CodingCatAsked:
Who is Participating?
 
jkrCommented:
BTW, in case you are compiling your app as UNICODE, you'll need to convert it to ANSI (char*) first, e.g.
          fileName[i] = (LPCTSTR)finder.GetFilePath();
 
          char tmp[MAX_PATH];
 
          wcstombs(tmp,(LPCTSTR)fileName[i],fileName[i].Length());
          someFunc(tmp);
          i++;

Open in new window

0
 
jkrCommented:
You can do that by using a 'LPCTSTR' cast as you are already using, e.g.
          fileName[i] = (LPCTSTR)finder.GetFilePath();
          someFunc((LPCTSTR)fileName[i]);
          i++;

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
CString has an operator LPCTSTR, which might be either wide (wchar_t *) or narrow (char *) depending upon your compile time settings. If you are building with Unicode enabled that your CString will be wide so there operator LPCTSTR will not be automatically invoked when you try and cast it to char *.

Try this...

someFunc((LPCTSTR)fileName[i]);

But note, if somefunc is only narrow (char *) and LPCTSTR is wide (wchar_t *) then the call to the function will fail.

You can convert wide to narrow using wcstombs

http://www.cplusplus.com/reference/clibrary/cstdlib/wcstombs/
0
 
CodingCatAuthor Commented:
It's the UNICODE issue again.
0
 
CodingCatAuthor Commented:
thanks for the link, evilrix.  wcstombs is necessary in my case.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.