These are Microsoft defined typedefs which correspond to:
LPCSTR: pointer to null terminated const string of char
LPSTR: pointer to null terminated char string of char
(often a buffer is passed and used as an 'output' param)
LPCWSTR: pointer to null terminated string of const wchar_t
LPWSTR: pointer to null terminated string of wchar_t
(often a buffer is passed and used as an 'output' param)
To "convert" a std::string
to a LPCSTR depends on the exact context but usually calling .c_str()
is sufficient.
This works.
void TakesString(LPCSTR param);
void f(const std::string& param)
{
TakesString(param.c_str());
}
Note that you shouldn't attempt to do something like this.
LPCSTR GetString()
{
std::string tmp("temporary");
return tmp.c_str();
}
The buffer returned by .c_str()
is owned by the std::string
instance and will only be valid until the string is next modified or destroyed.
To convert a std::string
to a LPWSTR
is more complicated. Wanting an LPWSTR
implies that you need a modifiable buffer and you also need to be sure that you understand what character encoding the std::string
is using. If the std::string
contains a string using the system default encoding (assuming windows, here), then you can find the length of the required wide character buffer and perform the transcoding using MultiByteToWideChar
(a Win32 API function).
e.g.
void f(const std:string& instr)
{
// Assumes std::string is encoded in the current Windows ANSI codepage
int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);
if (bufferlen == 0)
{
// Something went wrong. Perhaps, check GetLastError() and log.
return;
}
// Allocate new LPWSTR - must deallocate it later
LPWSTR widestr = new WCHAR[bufferlen + 1];
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// Do something with widestr
delete[] widestr;
}