Introduction
Because C-style strings are error-prone and difficult to manage, hackers even use a possible buffer overflow bug to target C-language-style strings, so many string encapsulation classes appear. Unfortunately, in some cases we don't know which string class to use, and we don't know how to convert a C-style string into a string wrapper class.
This article will introduce all the string types that appear in the Win32 API, MFC, STL, WTL, and Visual C + + run-time libraries. I'll describe the use of each class and tell you how to create objects for each class and how to convert a class to another class. The managed strings and the classes in Visual C + + 7 are nish.
To better benefit from this article, you have to understand the different character types and encodings that I introduced in the first section.
Rule #1 of string classes
It is not a good practice to use cast to implement type conversions unless a document explicitly states that the conversion is available.
The reason I'm writing these two articles is that some of the problems that are often encountered in string type conversions. When we use cast to convert a string from type X to type Z, we do not know why the code does not work properly. A wide variety of string types, especially BSTR, are rarely explicitly stated in any document in any place and can be cast to implement type conversions. So I think some people might use cast to implement type conversions and hopefully this transformation will work.
Cast does not convert any string unless the source string is a string wrapper class that is explicitly specified to support the conversion operator. Using cast for a constant string does not work, so the following code:
void SomeFunc ( LPCWSTR widestr );
main()
{
SomeFunc ( (LPCWSTR) "C:\\foo.txt" ); // WRONG!
}
Will surely fail. It can be compiled because the cast operation undoes the compiler's type check. However, compilation can pass and does not explain that the code is correct.
In the following example, I will indicate when the use of cast is legal.
C-style strings and typedefs
As I mentioned in the first section, Windows APIs are defined by TCHARs, which, at compile time, can be compiled into MBCS or Unicode characters depending on whether you define _MBCS or _unicode. You can see the full description of TCHAR in the first section, here for convenience, I have listed the character's typedefs
Type |
Meaning |
WCHAR |
Unicode character (wchar_t) |
TCHAR |
MBCS or Unicode character, depending on preprocessor settings |
LPSTR |
string of char (char*) |
Lpcstr |
Constant string of char (const char*) |
LPWStr |
string of WCHAR (wchar*) |
Lpcwstr |
Constant string of WCHAR (const wchar*) |
LPTSTR |
string of TCHAR (tchar*) |
Lpctstr |
Constant string of TCHAR (const tchar*) |