-1

I know this may be a silly question to an expert but I'm just wondering is it possible to pass a variable of type CString into a function declared below when called?

void LoadFile(char * szFileName);

The folowing error occurs: 'LoadFile' : cannot convert parameter 1 from 'class CString' to 'char *'...

Can I convert the string somehow?

Thankyou for your comments...

R2Delta
  • 29
  • 7
  • 5
    Almost certainly, but what is a `CString`? (It's not standard C++...) – Cameron Mar 12 '15 at 16:48
  • 2
    Possible duplicate of https://stackoverflow.com/questions/859304/convert-cstring-to-const-char – dhke Mar 12 '15 at 16:51
  • @Cameron: `CString` is a Microsoft-specific class. A Google search turned up this: https://msdn.microsoft.com/en-us/library/aa300688%28v=vs.60%29.aspx (Yes, that should have been explained in the question.) – Keith Thompson Mar 12 '15 at 17:15

3 Answers3

2

Freddy's answer is almost correct. The problem is really in the signature of LoadFile(). It probably should not be taking a char* argument. It should probably be taking a const char* argument. Are you planning on modifying the passed in string into LoadFile()? If not, make it const if the source is under your control--and if you won't break too many things.

In reality, you would have to do this:

CString filename("somefile.txt");
LoadFile((LPSTR)(LPCSTR) filename); // need the extra cast to (LPSTR)

or

LoadFile((LPSTR) filename.GetString()); 

This is all assuming you aren't building for Unicode. If you are building for Unicode, it's going to be different.

If you were building for Unicode, I would have changed the function signature to:

void LoadFile(LPCTSTR szFileName); // LPCTSTR == const TCHAR* (TCHAR is char for MBCS and wchar_t for Unicode)
Joseph Willcoxson
  • 5,853
  • 1
  • 15
  • 29
1

Your compiler is telling you exactly what is wrong. You're passing a custom object CString and the function you're calling is expecting a c-styled string (char * with a null terminator).

What you need is to access the c-style string that your CString class is wrapping. You can find more information about this at the MSDN documentation page here.

Simply cast your argument as an LPCSTR.

CString file("somefile.txt");
LoadFile((LPCSTR)file);
Freddy
  • 2,249
  • 1
  • 22
  • 31
0

Use the GetBuffer member function, which returns LPSTR...

https://msdn.microsoft.com/en-us/library/aa315043%28v=vs.60%29.aspx

ichramm
  • 6,437
  • 19
  • 30
  • `GetBuffer()` returns an `LPTSTR` (note the **T**). – dhke Mar 12 '15 at 16:50
  • yes, but the definition of `LPTSTR` depends on whether `UNICODE` is defined or not – ichramm Mar 12 '15 at 20:12
  • Exactly. And when `UNICODE` is defined, it's a `ẁchar_t *`, which does not convert to `char *`. As Joe notes in the answer above, the problem is actually more in the signature of `LoadFile()`. – dhke Mar 12 '15 at 20:16