1

I am trying to store some contents into a string variable by passing it as a parameter in various types of Windows API functions which accepts variable like char *.

For example, my code is:-

std::string myString;
GetCurrentDirectoryA( MAX_PATH, myString );

Now how do I convert the string variable to LPSTR in this case.

Please see, this function is not meant for passing the contents of string as input, but the function stores some contents into string variable after execution. So, myString.c_str( ) is ruled out.

Edit: I have a workaround solution of removing the concept of string and replacing it with something like

char myString[ MAX_PATH ];

but that is not my objective. I want to make use of string. Is there any way possible?

Also casting like

GetCurrentDirectoryA( MAX_PATH, ( LPSTR ) myString );

is not working.

Thanks in advance for the help.

Prasad
  • 5,946
  • 3
  • 30
  • 36

3 Answers3

7

Usually, people rewrite the Windows functions they need to be std::string friendly, like this:

std::string GetCurrentDirectoryA()
{
  char buffer[MAX_PATH];
  GetCurrentDirectoryA( MAX_PATH, buffer );
  return std::string(buffer);
}

or this for wide char support:

std::wstring GetCurrentDirectoryW()
{
  wchar_t buffer[MAX_PATH];
  GetCurrentDirectoryW( MAX_PATH, buffer );
  return std::wstring(buffer);
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
2

LPTSTR is defined as TCHAR*, so actually it is just an ordinary C-string, BUT it depends on whether you are working with ASCII or with Unicode in your code. So do

LPTSTR lpStr = new TCHAR[256];
ZeroMemory(lpStr, 256);
//fill the string using i.e. _tcscpy
const char* cpy = myString.c_str();
_tcscpy (lpStr, cpy);
//use lpStr

See here for a reference on _tcscpy and this thread.

Community
  • 1
  • 1
bash.d
  • 13,029
  • 3
  • 29
  • 42
  • Hi, did you mean .c_str( ) or is there something like .c_star( ). I am not able to search it. Also, I am using ASCII. So, according to my edited question, is the workaround solution given by me better or do you recommend me to use your proposed solution. Please can you contrast both the methods to me. – Prasad Apr 01 '13 at 06:56
  • It was the autocorrect of my tablet! I do mean `c_str()` of course! I use the generic approach which is common. In order to preserve genericity my approach is better. If you are fine with your approach then use it, as it provides a simpler, but non-generic way. – bash.d Apr 01 '13 at 07:02
1

Typically, I would read the data into a TCHAR and then copy it into my std::string. That's the simplest way.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62