[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 781
  • Last Modified:

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

0
CodingCat
Asked:
CodingCat
  • 2
  • 2
1 Solution
 
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
 
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
 
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

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now