I’m having trouble trying to cast a LPCWSTR to an LPCSTR.
Some Background
I am programming a VC++ 2010 application, and have already run into the situation where I had to convert from type System::String^ to std::string. I used this code to do so:
private: std::string toss(System::String^ s)
{
msclr::interop::marshal_context context;
return context.marshal_as<std::string>(s);
}
Doing so, I thought I would solve all my problems. I was wrong. From this, I need to cast a std::string as an LPCSTR, to use with some Windows API.
After reading some of the existing questions on SO, I feel like I am stuck. I was told to use:
LPCSTR str = existingstr.c_str();
When I use this, however, I am given the error: Cannot convert from LPCWSTR to LPCSTR
Does anyone have a better idea of what I should do in this specific case, or how I can convert from LPCWSTR to LPCSTR?
Thanks in advance.
Edit: completely misread the question so disregard my earlier answer, sorry. If you need to later pass this string into a Windows API, do you have a reason for using std::string and not std::wstring?
Additional edit: there’s some confusion on my part here. What is the type of existingstr and what is the signature of the Windows API function you’re calling? I think that would help clear things up. If existingstr is std::string, then .cstr() is compatible with LPCSTR (i.e. char const*). If existingstr is std::wstring, it is not. Is the API taking LPCSTR or LPCWSTR?
You could use this instead:
.c_str() on a std::wstring would result in a wchar_t const* (i.e. a LPCWSTR).