How can I convert a std::string to LPCSTR? Also, how can I convert a std::string to LPWSTR?
I am totally confused with these LPCSTR LPSTR LPWSTR and LPCWSTR.
Are LPWSTR and LPCWSTR the same?
Call c_str() to get a const char * (LPCSTR) from a std::string.
It's all in the name:
LPSTR - (long) pointer to string - char *
LPCSTR - (long) pointer to constant string - const char *
LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).
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;
}
Using LPWSTR you could change contents of string where it points to. Using LPCWSTR you couldn't change contents of string where it points to.
std::string s = SOME_STRING;
// get temporary LPSTR (not really safe)
LPSTR pst = &s[0];
// get temporary LPCSTR (pretty safe)
LPCSTR pcstr = s.c_str();
// convert to std::wstring
std::wstring ws;
ws.assign( s.begin(), s.end() );
// get temporary LPWSTR (not really safe)
LPWSTR pwst = &ws[0];
// get temporary LPCWSTR (pretty safe)
LPCWSTR pcwstr = ws.c_str();
LPWSTR is just a pointer to original string. You shouldn't return it from function using the sample above. To get not temporary LPWSTR you should made a copy of original string on the heap. Check the sample below:
LPWSTR ConvertToLPWSTR( const std::string& s )
{
LPWSTR ws = new wchar_t[s.size()+1]; // +1 for zero at the end
copy( s.begin(), s.end(), ws );
ws[s.size()] = 0; // zero at the end
return ws;
}
void f()
{
std::string s = SOME_STRING;
LPWSTR ws = ConvertToLPWSTR( s );
// some actions
delete[] ws; // caller responsible for deletion
}
The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*, widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.
One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.
Converting is simple:
std::string myString;
LPCSTR lpMyString = myString.c_str();
One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.
The conversion is simple:
std::string str;
LPCSTR lpcstr = str.c_str();
The easiest way to convert a std::string to a LPWSTR is in my opinion:
Convert the std::string to a std::vector<wchar_t>
Take the address of the first wchar_t in the vector.
std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.
std::string myString("SomeValue");
LPSTR lpSTR = const_cast<char*>(myString.c_str());
myString is the input string and lpSTR is it's LPSTR equivalent.
Related
How can I convert a std::string to LPCSTR? Also, how can I convert a std::string to LPWSTR?
I am totally confused with these LPCSTR LPSTR LPWSTR and LPCWSTR.
Are LPWSTR and LPCWSTR the same?
Call c_str() to get a const char * (LPCSTR) from a std::string.
It's all in the name:
LPSTR - (long) pointer to string - char *
LPCSTR - (long) pointer to constant string - const char *
LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).
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;
}
Using LPWSTR you could change contents of string where it points to. Using LPCWSTR you couldn't change contents of string where it points to.
std::string s = SOME_STRING;
// get temporary LPSTR (not really safe)
LPSTR pst = &s[0];
// get temporary LPCSTR (pretty safe)
LPCSTR pcstr = s.c_str();
// convert to std::wstring
std::wstring ws;
ws.assign( s.begin(), s.end() );
// get temporary LPWSTR (not really safe)
LPWSTR pwst = &ws[0];
// get temporary LPCWSTR (pretty safe)
LPCWSTR pcwstr = ws.c_str();
LPWSTR is just a pointer to original string. You shouldn't return it from function using the sample above. To get not temporary LPWSTR you should made a copy of original string on the heap. Check the sample below:
LPWSTR ConvertToLPWSTR( const std::string& s )
{
LPWSTR ws = new wchar_t[s.size()+1]; // +1 for zero at the end
copy( s.begin(), s.end(), ws );
ws[s.size()] = 0; // zero at the end
return ws;
}
void f()
{
std::string s = SOME_STRING;
LPWSTR ws = ConvertToLPWSTR( s );
// some actions
delete[] ws; // caller responsible for deletion
}
The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*, widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.
One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.
Converting is simple:
std::string myString;
LPCSTR lpMyString = myString.c_str();
One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.
The conversion is simple:
std::string str;
LPCSTR lpcstr = str.c_str();
The easiest way to convert a std::string to a LPWSTR is in my opinion:
Convert the std::string to a std::vector<wchar_t>
Take the address of the first wchar_t in the vector.
std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.
std::string myString("SomeValue");
LPSTR lpSTR = const_cast<char*>(myString.c_str());
myString is the input string and lpSTR is it's LPSTR equivalent.
I want to use MoveFile function, this function use two LPWSTR arguments, but I have one char* and LWSTR, how to concatenate them?
//move file
LPWSTR latestFile = L"test.SPL";
char* spoolFolder = "C:\\Windows\\System32\\spool\PRINTERS\\";
LPWSTR fileToMove = spoolFolder + latestFile;
BOOL moved = MoveFile(latestFile, L"C:\\UnprocessedFiles\\" + latestFile);
Just for clarification, LPWSTR is a typedef for wchar_t*. You can use wcscat_s to conctenate strings of this form. Your one char* string should just be changed to be of the same type, since you have it there as a simple literal (just prefix the literal with L and change the declared type). Since you tagged this as C++, however, you can do all of this more simply by using the std::wstring class.
std::wstring latestFile = wstring("test.SPL");
std::wstring spoolFolder = wstring("C:\\Windows\\System32\\spool\PRINTERS\\");
std::wstring fileToMove = spoolFolder + latestFile;
BOOL moved = MoveFile(latestFile.c_str(), fileToMove.c_str());
In deed, LPWSTR is just a typdef for w_char*. so if you consult MSDN you will see that:
typded wchar_t* LPWSTR;
here the w_char* means that your string will be encoded as UNICODE not ANSI scheme. So under windows a UNICODE string will be an UTF16 one ( 2 bytes for each char).
std::wstring is also a typedef for std::basic_string<wchar_t,char_traits<>> so by declaring your inputs as wstring and calling wasting.c_str() this will do the stuff.
What are the steps I have to take to duplicate a LPCWSTR string?
Consider the case: LPCWSTR str = L"Copy me";
Use wcscpy(). Here is the MSDN documentation:
http://msdn.microsoft.com/en-us/library/kk6xf663(v=vs.90).aspx
A safer variant is wcscpy_s(). You have to allocate a buffer that is big enough to hold the copy up front:
LPCWSTR str = L"Copy me";
std::vector<wchar_t> thecopy( wcslen(str) + 1 ); // add one for null terminator
wcscpy_s(thecopy.data(), thecopy.size(), str);
// you can get a pointer to the copy this way:
LPCWSTR *strCopy = thecopy.data();
wcscpy_s()'s documentation can be found here:
http://msdn.microsoft.com/en-us/library/td1esda9(v=vs.90).aspx
Use wcscpy
LPWSTR wcscpy(LPWSTR szTarget, LPWCSTR szSource);
Target is non-constant wide-string (LPWSTR), and source is constant-wide-string.
LPCWSTR is defined as
typedef const WCHAR* LPCWSTR;
LP - Pointer
C - Constant
WSTR - Wide character String
Assuming LPCWSTR is equvivalent to const wchar_t * then for GNU systems you can use wcsdup():
wchar_t * wcsdup(const wchar_t * s);
The function is also defined by POSIX.1-2008.
How can I convert a std::string to LPCSTR? Also, how can I convert a std::string to LPWSTR?
I am totally confused with these LPCSTR LPSTR LPWSTR and LPCWSTR.
Are LPWSTR and LPCWSTR the same?
Call c_str() to get a const char * (LPCSTR) from a std::string.
It's all in the name:
LPSTR - (long) pointer to string - char *
LPCSTR - (long) pointer to constant string - const char *
LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).
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;
}
Using LPWSTR you could change contents of string where it points to. Using LPCWSTR you couldn't change contents of string where it points to.
std::string s = SOME_STRING;
// get temporary LPSTR (not really safe)
LPSTR pst = &s[0];
// get temporary LPCSTR (pretty safe)
LPCSTR pcstr = s.c_str();
// convert to std::wstring
std::wstring ws;
ws.assign( s.begin(), s.end() );
// get temporary LPWSTR (not really safe)
LPWSTR pwst = &ws[0];
// get temporary LPCWSTR (pretty safe)
LPCWSTR pcwstr = ws.c_str();
LPWSTR is just a pointer to original string. You shouldn't return it from function using the sample above. To get not temporary LPWSTR you should made a copy of original string on the heap. Check the sample below:
LPWSTR ConvertToLPWSTR( const std::string& s )
{
LPWSTR ws = new wchar_t[s.size()+1]; // +1 for zero at the end
copy( s.begin(), s.end(), ws );
ws[s.size()] = 0; // zero at the end
return ws;
}
void f()
{
std::string s = SOME_STRING;
LPWSTR ws = ConvertToLPWSTR( s );
// some actions
delete[] ws; // caller responsible for deletion
}
The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*, widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.
One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.
Converting is simple:
std::string myString;
LPCSTR lpMyString = myString.c_str();
One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.
The conversion is simple:
std::string str;
LPCSTR lpcstr = str.c_str();
The easiest way to convert a std::string to a LPWSTR is in my opinion:
Convert the std::string to a std::vector<wchar_t>
Take the address of the first wchar_t in the vector.
std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.
std::string myString("SomeValue");
LPSTR lpSTR = const_cast<char*>(myString.c_str());
myString is the input string and lpSTR is it's LPSTR equivalent.
Can anyone help in converting string to LPWSTR
string command=obj.getInstallationPath()+"<some string appended>"
Now i wat to pass it as parameter for CreateProcessW(xx,command,x...)
But createProcessW() accepts only LPWSTR so i need to cast string to LPWSTR
Thanks in Advance
If you have an ANSI string, then have you considered calling CreateProcessA instead? If there is a specific reason you need to call CreateProcessW then you will need to convert the string. Try the MultiByteToWideChar function.
Another way:
mbstowcs_s
use with string.c_str(), you can find example here or here
OR
USES_CONVERSION_EX;
std::string text = "text";
LPWSTR lp = A2W_EX(text.c_str(), text.length());
OR
{
std::string str = "String to LPWSTR";
BSTR b = _com_util::ConvertStringToBSTR(str.c_str());
LPWSTR lp = b;
Use lp before SysFreeString...
SysFreeString(b);
}
The easiest way to convert an ansi string to a wide (unicode) string is to use the string conversion macros.
To use these, put USES_CONVERSION at the top of your function, then you can use macros like A2W() to perform the conversion very easily.
eg.
char* sz = "tadaaa";
CreateProcessW(A2W(sz), ...);
The macros allocate space on the stack, perform the conversion and return the converted string.
Also, you might want to consider using TCHAR throughout... If I'm correct, the idea would be something like this:
typedef std::basic_string<TCHAR> tstring
// Make any methods you control return tstring values. Thus, you could write:
tstring command = obj.getInstallationPath();
CreateProcess(x, command.c_str(), ...);
Note that we use CreateProcess instead of CreateProcessW or CreateProcessA. The idea is that if UNICODE is defined, then TCHAR is typedefed to WCHAR and CreateProcess is #defined to be CreateProcessW, which accepts a LPWSTR; but if UNICODE is not defined, then TCHAR becomes char, and CreateProcess becomes CreateProcessA, which accepts a LPSTR. But I might not have the details right here... this stuff seems somewhat needlessly complicated :(.
Here is another option. I've been using this function to do the conversion.
//C++ string to WINDOWS UNICODE string
std::wstring s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
And wrap your string like this.
s2ws( volume.c_str())