Prasad
Prasad

Reputation: 6034

How to convert string to LPSTR in WinAPI function which stores output in string

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.

Upvotes: 1

Views: 8635

Answers (3)

Simon Mourier
Simon Mourier

Reputation: 138776

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);
}

Upvotes: 7

bash.d
bash.d

Reputation: 13207

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.

Upvotes: 2

StilesCrisis
StilesCrisis

Reputation: 16290

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

Upvotes: 1

Related Questions