Relationship and difference between CString, BSTR, and LPCTSTR
CString is a dynamic TCHAR array, and BSTR is a string in a proprietary format (it needs to be manipulated using the functions provided by the system. The LPCTSTR is just a constant TCHAR pointer. CString is a completely independent class, dynamic TCHAR array, and encapsulates operators such as + and string operation methods. Typedef olechar far * BSTR; Typedef const char * LPCTSTR; Representation of various strings in vc ++
First, char * is a pointer to an ANSI character array, where each character occupies 8 bits (valid data is to remove the other seven bits), which is consistent with the traditional C, C ++ compatibility.
LP indicates a long pointer ). LPSTR is a pointer to an ANSI character array ending with '\ 0'. It can be used interchangeably with char *, and LPSTR is often used in win32. The 'C' added in the LPCSTR indicates "CONSTANT" (CONSTANT), indicating that this data type instance cannot be changed by using its API function. In addition, it is equivalent to LPSTR. 1. LP indicates a long pointer. In win16, there is a difference between a long pointer (LP) and a short pointer (P). In win32, there is no difference, both 32-bit. therefore, the LP and P here are equivalent. 2. C Indicates const 3. What is T? We know that TCHAR is wchar_t in Unicode mode and compiled into char in general.
In order to meet the international needs of the program code, the industry has introduced the Unicode Standard, which provides a simple and consistent expression of the string method, all characters in the byte is a 16-bit value, the number of characters can also meet the encoding requirements of almost all written language characters in the world. Unicode (type: wchar_t) is an encouraging practice during development.
This produces LPWSTR and LPCWSTR. Their meanings are similar to LPSTR and LPCSTR, except that the character data is a 16-bit wchar_t instead of a char.
In order to realize the common use of the two types of encoding, TCHAR is defined as follows: If _ UNICODE is defined, the Declaration is as follows: Typedef wchar_t TCHAR; If _ UNICODE is not defined, the Declaration is as follows: Typedef char TCHAR;
The meaning in LPTSTR and LPCTSTR is that each character is such a TCHAR.
The characters in the CString class are declared as TCHAR type. It provides an encapsulated class for your convenience.
LPCTSTR: # Ifdef _ UNICODE Typedef const wchar_t * LPCTSTR; # Else Typedef const char * LPCTSTR; # Endif
Conversion of common VC Data Types
First, some common types of variables are defined to illustrate Int I = 100; Long l = 2001; Float f = 300.2; Double d = 12345.119; Char username [] = "Woman Cheng peijun "; Char temp [200]; Char * buf; CString str; _ Variant_t v1; _ Bstr_t v2;
1. convert other data types to strings
Short INTEGER (int) Itoa (I, temp, 10); // convert I to a string and put it into temp. the last digit indicates decimal. Itoa (I, temp, 2); // Binary Conversion Long (long) Ltoa (l, temp, 10 );
2. Obtain the pointer to the string from other variables containing the string
CString variable Str = "2008 Beijing Olympics "; Buf = (LPSTR) (LPCTSTR) str; _ Variant_t variable of the BSTR type V1 = (_ bstr_t) "programmer "; Buf = _ com_util: ConvertBSTRToString (_ bstr_t) v1 );
Iii. Convert strings to other data types Strcpy (temp, "123 ");
Short INTEGER (int) I = atoi (temp ); Long (long) L = atol (temp ); Floating Point (double) D = atof (temp );
4. convert other data types to CString
Use the CString member function Format for conversion. For example:
INTEGER (int) Str. Format ("% d", I ); Float) Str. Format ("% f", I ); Data Types supported by CString constructors, such as string pointers (char *), can be directly assigned values. Str = username;
V. BSTR, _ bstr_t and CComBSTR
CComBSTR and _ bstr_t are encapsulation of BSTR, and BSTR is a 32-bit pointer to a string. Char * can be converted to BSTR like this: BSTR B = _ com_util: ConvertStringToBSTR ("data"); // you need to add the header file comutil. h before use Otherwise, use char * p = _ com_util: ConvertBSTRToString (B );
6. VARIANT, _ variant_t, and COleVariant
For the VARIANT Structure, refer to the definition of the tagVARIANT struct in the header file VC98 \ Include \ OAIDL. H. Assign a value to the VARIANT variable: assign a value to the vt member to specify the data type, and then assign a value to the variable of the same data type in the union structure. For example: VARIANT va; Int a = 2001; Va. vt = VT_I4; // specify Integer Data Va. lVal = a; // value assignment
For VARIANT that is not immediately assigned a value, it is best to initialize with Void VariantInit (variantarg far * pvarg); in essence, the vt is set to VT_EMPTY, the following table lists the correspondence between vt and common data:
Unsigned char bVal; VT_UI1 Short iVal; VT_I2 Long lVal; VT_I4 Float fltVal; VT_R4 Double dblVal; VT_R8 VARIANT_BOOL boolVal; VT_BOOL SCODE scode; VT_ERROR CY cyVal; VT_CY DATE date; VT_DATE BSTR bstrVal; VT_BSTR IUnknown FAR * punkVal; VT_UNKNOWN IDispatch FAR * pdispVal; VT_DISPATCH Safearray far * parray; VT_ARRAY | * Unsigned char FAR * pbVal; VT_BYREF | VT_UI1 Short FAR * piVal; VT_BYREF | VT_I2 Long FAR * plVal; VT_BYREF | VT_I4 Float FAR * pfltVal; VT_BYREF | VT_R4 Double FAR * pdblVal; VT_BYREF | VT_R8 VARIANT_BOOL FAR * pboolVal; VT_BYREF | VT_BOOL Scode far * pscode; VT_BYREF | VT_ERROR Cy far * pcyVal; VT_BYREF | VT_CY Date far * pdate; VT_BYREF | VT_DATE Bstr far * pbstrVal; VT_BYREF | VT_BSTR IUnknown FAR * ppunkVal; VT_BYREF | VT_UNKNOWN IDispatch FAR * ppdispVal; VT_BYREF | VT_DISPATCH Safearray far * pparray; VT_ARRAY | * Variant far * pvarVal; VT_BYREF | VT_VARIANT Void FAR * byref; VT_BYREF
_ Variant_t is the encapsulation class of VARIANT, and its value assignment can be forced type conversion. Its constructor will automatically process these data types. For example: Long l = 222; Ing I = 100; _ Variant_t lVal (l ); LVal = (long) I;
The use of COleVariant is basically the same as that of the _ variant_t method. See the following example: COleVariant v3 = "string", v4 = (long) 1999; CString str = (BSTR) v3.pbstrVal; Long I = v4.lVal;
VII. Others
During message processing, we often need to split WPARAM, LPARAM, and other 32-bit data (DWORD) into two 16-bit data (WORD), for example: LPARAM lParam; WORD loValue = LOWORD (lParam); // take 16 bits WORD hiValue = HIWORD (lParam); // The height is 16 bits. For a 16-bit data (WORD), we can use the same method to break down the high and low 8-bit data (BYTE), for example: WORD wValue; BYTE loValue = LOBYTE (wValue); // get 8 bits BYTE hiValue = HIBYTE (wValue); // The value is 8 bits in height. How to assign a variable of the CString type to a variable of the char * type 1. GetBuffer function: Use the CString: GetBuffer function. Char * p; CString str = "hello "; P = str. GetBuffer (str. GetLength ()); Str. ReleaseBuffer ();
When converting CString to char * CString str ("aaaaaaa "); Strcpy (str. GetBuffer (10), "aa "); Str. ReleaseBuffer (); Call GetBuffer (int n) when we need a character array, where n is the length of the character array we need. Call ReleaseBuffer () immediately after use (); It is also important that you do not use char * Where const char * can be used *
2. memcpy: CString mCS = _ T ("cxl "); Char mch [20]; Memcpy (mch, mCS, 20 );
3. Use LPCTSTR for forced conversion: Do not use it whenever possible Char * ch; CString str; Ch = (LPSTR) (LPCTSTR) str;
CString str = "good "; Char * tmp; Sprintf (tmp, "% s", (LPTSTR) (LPCTSTR) str );
4, CString Msg; Msg = Msg + "abc "; LPTSTR lpsz; Lpsz = new TCHAR [Msg. GetLength () + 1]; _ Tcscpy (lpsz, Msg ); Char * psz; Strcpy (psz, lpsz );
CString class to const char * Conversion Char a [100]; CString str ("aaaaaa "); Strncpy (a, (LPCTSTR) str, sizeof ()); Or: Strncpy (a, str, sizeof ()); The preceding two methods are correct. Because the second parameter type of strncpy is const char *, the compiler automatically converts the CString class to const char *.
CString to LPCTSTR (const char *) CString cStr; Const char * maid = (lpctStr) cStr;
Convert the string type to the string type Maid; CString cStr = lpctStr;
Assign a char * type variable to a CString type variable. Values can be assigned directly, for example: CString myString = "This is a test "; You can also use constructors, such: CString s1 ("Tom ");
Assign a variable of the CString type to a variable of the char [] type (string ). 1. sprintf () function CString str = "good "; Char tmp [200]; Sprintf (tmp, "% s", (LPCSTR) str ); This forced conversion is equivalent to (LPTSTR) (LPCTSTR) str When the CString class variables need to be converted to (char *), use (LPTSTR) (LPCTSTR) str
However, the LPCTSTR is const char *, that is, the resulting string cannot be written! It is extremely dangerous to forcibly convert it to LPTSTR to remove const! If you don't care, you will be finished! To obtain char *, use GetBuffer () or GetBufferSetLength (). Call ReleaseBuffer () after use ().
2. strcpy () function CString str; Char c [256]; Strcpy (c, str );
Char mychar [1024]; CString source = "Hello "; Strcpy (char *) & mychar, (LPCTSTR) source );
Use of CString 1. Specify CString Parameters For most functions that require string parameters, it is best to specify the form parameter in the function prototype as a const pointer pointing to the character (LPCTSTR) rather than the CString. When you specify a parameter as a const pointer to a character, you can pass the pointer to a TCHAR array (such as a string ["hi there"]) or to a CString object. The CString object is automatically converted to the LPCTSTR. CString objects can also be used wherever the LPCTSTR can be used.
2. If a parameter is not modified, the parameter is also specified as a constant string reference (const CString &). If the function needs to modify the string, Delete the const modifier. If the default value is null, initialize it as a Null String [""], as shown below: Void AddCustomer (const CString & name, const CString & address, const CString & comment = "");
3. For most function results, return the CString object by value.
Basic string operations Many advanced Languages provide operators or standard library functions for basic string operations. To facilitate the description, first define several related variables: Char s1 [20] = "dir/bin/appl", s2 [20] = "file. asm", s3 [30], * p; Int result; The following describes the basic operations of strings in C language. 1. Obtain the string length Int strlen (char * s); // evaluate the length of string s [Example] printf ("% d", strlen (s1); // output the string length of s1 12
2. String Replication Char * strcpy (char * to, * from); // copy the from string to string and return the pointer to start [Example] strcpy (s3, s1); // s3 = "dir/bin/appl", s1 string unchanged
3. Join Char * strcat (char * to, char * from); // copy the from string to the end of the string, // Returns the pointer at the beginning of the to string. [Example] strcat (s3, "/"); // s3 = "dir/bin/appl /" Strcat (s3, s2); // s3 = "dir/bin/appl/file. asm"
4. String comparison Int strcmp (char * s1, char * s2); // compare the sizes of s1 and s2, // When s1 <s2, s1> s2 and s1 = s2, return values smaller than 0, greater than 0, and equal to 0, respectively. [Example] result = strcmp ("baker", "Baker"); // result> 0 Result = strcmp ("12", "12"); // result = 0 Result = strcmp ("Joe", "joseph") // result <0
5. Character locating Char * strchr (char * s, char c); // locate the first occurrence of c in string s, // If it is found, the location is returned; otherwise, NULL is returned. [Example] p = strchr (s2, '.'); // p points to the position after "file ". If (p) strcpy (p, ". cpp"); // s2 = "file. cpp"
Note: ① The above operations are the most basic, among which the last four operations are also variant forms: strncpy, strncath and strnchr. ② For other string operations, see <string. h> of C. In different advanced languages, the types and symbols of string operations are different. ③ Other string operations can generally be combined by these basic operations
[Example] The Sub-string operation can be implemented as follows: Void substr (char * sub, char * s, int pos, int len ){ // S and sub are character arrays. sub is used to return the substring whose length is len starting from the second pos character of string s. // 0 <= pos <= strlen (s)-1, and the array sub can contain at least len + 1 characters. If (pos <0 | pos> strlen (s)-1 | len <0) Error ("parameter error! "); Strncpy (sub, & s [pos], len); // copy up to len characters from s [pos] to sub
|