Application and difference of CString, BSTR, and LPCTSTR

Source: Internet
Author: User
Tags constant constructor float double function prototype sprintf strcmp strlen win32

Application and difference of cstring, bstr, and lpctstr

I. Definition

Cstring is a useful data type. They greatly simplify many operations in mfc, making it much easier for mfc to perform string operations. In any case, there are many special skills to use cstring, especially for programmers coming out of the pure c background.


1. cstring: Dynamic tchar array. It is a completely independent class that encapsulates the + operator and string operation method.

2. bstr: a string in a proprietary format (which must be manipulated using system functions ). Defined as: typedef olechar far * bstr

Because bstr is a string that records unicode characters, you can use the standard conversion method to create an 8-bit cstring. In fact, this is the built-in function of cstring. A special constructor in cstring can convert ansi to unicode or unicode to ansi. You can also obtain bstr strings from variant variables. The variant type is returned by various com and automation (automation) calls.

3. lpctstr: tchar pointer of a constant. Defined as: typedef const char * lpctstr

Lpctstr type: l indicates the long pointer, which is left behind by a 16-bit operating system such as windows 3.1. In win32 and other 32-bit operating systems, long pointers, near pointers, and far modifiers are designed for compatibility. No practical significance. P indicates that this is a pointer. c indicates that it is a constant. t indicates that in the win32 environment, there is a _ t macro. str indicates that this variable is a string.

II. Key points

1. char *: pointer to the ansi character array, where each character occupies 8 bits (valid data is the other seven bits of the highest bits), which maintains

Compatible with traditional c/c ++.

2. lps tutorial tr: a pointer to an ansi character array ending with "", which can be used interchangeably with char *, which is usually used in win32.

Lp indicates a long pointer ).

3. lpcstr: the feature of this data type is that its instance cannot be changed by using its api function, which is equivalent to lpstr. Its

Constant ).

4. In win16, long pointers (lp) and short pointers (p) are different. In win32, they are all 32-bit.

5. When tchar is compiled in unicode mode, it is wchar_t and the time-bit char is compiled in normal encoding mode.

III. unicode standard

1. In order to meet the international needs of the program code, the industry has introduced the unicode standard, which provides a simple and consistent string representation

The number of bytes in all characters is a 16-bit (two-byte) value.

Encoding requirements. unicode (wchar_t) is an encouraging practice.

2. This is the result of lpwstr and lpcwstr. Their meanings are similar to lpstr and lpcstr. The difference is that wchar_t is

16 bits, while char is 8 bits.

IV. tchar data type

The tchar data type is proposed to realize the common ansi and unicode encoding.

1. If _ unicode is defined, the declaration is as follows:

Typedef wchar_t tchar;

2. If _ unicode is not defined, the declaration is as follows:

Typedef char tchar;

In this way, each character in cstring, lptstr, and lpctstr can be of the tchar type, regardless of their encoding format.

. In addition, cstring is an encapsulated class, which greatly facilitates your use.

5. Conversion between common data types in vc ++

1. Definition

Int I = 100;

Long l = 2001;

Float f = 300.2;

Double d = 12345.119

Char username [] = "2008 Beijing Olympics ";

Char temp [200];

Char * buf;

Cstring str;

_ Variant_t v1;

_ Bstr_t v2;

2. Conversion from other data types to strings

(1) Short integer int-> string

Itoa (I, temp, 10); // converts I to a string in decimal format and stores it in temp.

Itoa (I, temp, 2); // converts I to a string in binary format and stores it in temp.

(2) long integer long-> string

Ltoa (l, temp, 10 );

3. Obtain the pointer to the string from other variables that contain the string.

(1) obtain the string from the cstring variable

Str = "Pray for Sichuan ";

Buf = (lpstr) (lpctstr) str;

(2) obtain the string from the _ varitant_t variable of the bstr type

V1 = (_ bstr_t) "programmer ";

Buf = _ com_util: convertbstrtostring (_ bstr_t) v1 );

4. String conversion to other data types

Strcpy (temp, "123 ");

(1) I = atoi (temp); // string-> Short integer int

(2) l = atol (temp); // string-> long integer long

(3) d = atof (temp); // string-> float double

5. Convert other data types to cstring

(1) use the cstring member function format for conversion

A: str. format ("% d", I); // Short integer int-> cstring

B: str. format ("% f", f); // floating point float-> cstring

(2) data types that support cstring constructors can be directly assigned values, such as char *

Str = username;

6. bstr, _ bstr_t, and ccombbstr

Bstr: a 32-bit pointer to a string. Both _ bstr_t and ccombstr encapsulate the string.

1. Conversion of char *-> bstr

Bstr B = _ com_util: convertstringtobstr ("data ");

Note: The comutil. h header file must be added before use.

2. Conversion of bstr-> char *

Char * p = _ com_util: convertbstrtostring (B );

7. variant, _ variant_t, and colevariant

1. Assign a value to the variant variable: assign a value to the vt member to specify the data type. Then, assign variables of the same data type to the union structure.

Value (see the definition of the tagvariant struct in the vc98inludeoaidl. h header file ). Example:

Variant va;

Va. vt = vt_l4; // specify the data type

Va. lval = 2008;

2. For variant without immediate value assignment, it is best to use the void variantinit (variantarg far * pvarg) function to initialize it.

In essence, vt is set to vt_empty. The correspondence between vt and common data types (omitted ).

3. _ variant_t is the encapsulation class of variant. You can use forced type conversion to assign values. The constructor automatically processes these data types.

For example:

Long l = 222;

Int I = 100;

_ Variant_t lval (l );

Lval = (long) I;

4. The usage of colevariant and _ variant_t is basically the same. The example is as follows:

Colevariant v3 = "string", v4 = (long) 1999;

Cstring str = (bstr) v3.pbstrval;

Long l = v4.lval;

VIII. Others

1. During message processing, we usually need to split wparam, lparam, and other 32-bit data (dword) into two 16-bit data.

(Word), for example:

Lparam;

Word lovalue = loword (lparam); // take 16 bits

Word hivalue = hiword (lparam); // The height is 16 bits.

2. For 16-bit data (word), we can use the same method to break down the data into two 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.

3. How to assign a variable of the cstring type to a variable of the char * type?

(1) cstring: getbuffer function

Char * p;

Cstring str = "hello ";

P = str. getbuffer (str. getlength ());

Str. releasebuffer ();

(2) strcpy function

Cstring str ("aaaaaaaa ");

Strcpy (str. getbuffer (10), "aa ");

Str. releasebuffer ();

The getbuffer (int n) function is used to obtain the character array, where n represents the length of the character array. After using this character array, you must call

Releasebuffer () function to release this character array.

Note: Do not use char * unless const char * can be used *

(3) memcpy function

Cstring mcs = _ t ("cxl ");

Char mch [20];

Memcpy (mch, mcs, 20 );

(4) forced type conversion (not recommended)

Char * ch;

Cstring str;

Ch = (lpstr) (lpctstr) str;

Str = "good! ";

Sprintf (ch, "% s", (lptstr) (lpctstr) str );

(5) cstring-> lptstr-> char *

Cstring msg;

Msg = msg + "abc ";

Lptstr lpsz;

Lpsz = new tchar [msg. getlength () + 1];

_ Tcscpy (lpsz, msg );

Char * psz;

Strcpy (psz, lpsz );

4. How to assign a variable of the cstring type to a variable of the const char * type?

Char * a [100];

Cstring str ("abcdef ");

Strncpy (a, (lpctstr) str, sizeof ());

Or

Strncpy (a, str, sizeof ());

Note: The compiler automatically converts the cstring type variable to the const char * type.

5. How to assign a cstring type variable to a variable of the lpctstr type?

Cstring cstr;

Const char * maid = (lpctstr) cstr;

6. How to assign a variable of the lpctstr type to a variable of the cstring type?

Maid;

Cstring cstr = lpctstr;

7. How to assign a char * type variable to a cstring type variable

(1) direct value assignment: cstring mystring = "this is a test ";

(2) constructor: cstring s1 ("tom ");

8. How to assign a variable of the cstring type to a variable of the char [] (string) type?

(1) sprintf function

Cstring str = "good! ";

Char temp [200];

Sprintf (temp, "% s", (lpcstr) str );

Note: Forced type conversion (lpcstr) str is the same as (lptstr) (lpctstr) str. The difference is that the cstring object is a variable.

Or a constant. The lpctstr indicates const char *, and the resulting string cannot be written! If you forcibly convert it to an lptstr (

Remove const), it is extremely dangerous! To get char *, use the getbuffer or getbuffersetlength function.

Use the releasebuffer function.

(2) strcpy function

Cstring str;

Char c [256];

Strcpy (c, str );

Str = "hello ";

Strcpy (char *) & c, (lpctstr) str );

9. Use of cstring

1. Specify cstring parameters

(1) for most functions that require string parameters, it is best to specify the form parameter in the function prototype as a pointing character (lpctstr) instead

The const pointer of 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"

Here "] or passed to the cstring object ). The cstring object is automatically converted to the lpctstr. Any place that can use lpctstr can also

Use the cstring object.

(2) If a parameter is not modified, the parameter is also specified as a constant string reference (const cstring &). If the function is to be modified

To 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 the results of most functions, return the cstring object by value.

2. Basic string operations

Char s1 [20] = "dir/bin/appl", s2 [20] = "file. asm", s3 [30], * p;

Int result;

(1) evaluate the string length

Int strlen (char * s); // Evaluate the length of string s

Example: printf ("% d", strlen (s1 ));

(2) string replication

Char * strcpy (char * to, char * from); // Copy the from string to string and return the pointer at the beginning of "".

Example: strcpy (s3, s1 );

(3) connection

Char * strcat (char * to, char * from); // Copy the from string to the end of the to string

Example: strcat (s3 ,"/");

Strcat (s3, s2 );

(4) string comparison

Int strcmp (char * s1, char * s2); // compare the sizes of s1 and s2, s1 <s2 (less than 0), s1 = s2 (0) and s1> s2 (greater than 0)

Example: result = strcmp ("baker", "baker"); // greater than 0

Result = strcmp ("12", "12"); // 0

Result = strcmp ("joe", "joseph"); // less than 0

(5) character locating

Char * strchr (char * s, char c); // locate the first occurrence of c in string s. If yes, the location is returned; otherwise, null is returned.

For example, p = strchr (s2, '.'); // p points to the position after "file".

(6) note

A: The preceding operations are the most basic. The last four operations also have variant forms: strncpy, strncath, and strnchr.

B: For other string operations, see the header file <string. h> of c. In different advanced languages, the types and symbols of string operations are different.

C: other string operations can generally be combined by these basic operations.

For example, the sub-string operation can be implemented as follows:

// S and sub are character arrays. sub is used to return the substring whose second pos character length is len.

Void substr (char * sub, char * s, int pos, int len)

    {

// 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! ");

// Copy up to len characters to sub from s [pos]

Strncpy (sub, * s [pos], len );

    }

Between getbuffer and releasebuffer, the memory allocated by cstring is handled by you, so you cannot call other cstring functions. Cstring to lpctstr: cstring cstr; const char * lpctstr = (lpctstr) cstr; lpctstr to cstring: lpctstr; cstring cstr = lpctstr;


The above are some tips for using cstring. I use it every day when writing a program. Cstring is not a very difficult class to use, but mfc does not clearly point out these features and you need to explore them yourself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.