Discuss a BSTR type conversion problem together

zhaozj2021-02-08  449

[Summary and translate from MSDN] [BSTR ​​and string operation]

1. Use _BSTR_T to solve memory problems

One important topic in COM program is to maintain BSTR type variables. In some cases (mainly when passing or copying BSTR type data), some issues are generated: * Function cannot receive variable parameters of the BSTR type * When copying BSTR type data Resulting in memory leakage

Usually using the _bstr_t object can solve these problems, this object encapsulates the BSTR data type, automatically performs the distribution management of resources, and provides an automatic data type conversion operation.

Note: Use the mandatory type conversion _BSTR_T to the Unicode mode link is not applicable, you need to use the Win32 mode link.

In addition, there is also a memory management problem, use the assignment mode will have a memory leak: BSTR tmpBStr; m_pObject1-> get_ObjectString (& tmpBStr); _bstr_t tmpbstr; tmpbstr = tmpBStr; // memory leaks SetDlgItemText (IDC_CURPROPVAL, tmpbstr);

Leakage occurs when the TMPBSTR variable is initialized, the function sysallocstring is automatically called when the TMPBSTR variable is created. This new application is not released, causing memory leakage.

2. BSTR Data Type 1) BSTR, LPWSTR and LPSTR LPSTR is the macro definition of a MFC of our daily use of MFC, using a resource for LPWSTR more than LPSTR, because it uses double-bytes to express a character like it and Chinese characters The BSTR has an additional data length to store the data length.

2) How to convert LPSTR / LPCTSTR to BSTR / LPWSTR actually MFC / ATL provides a set of macro definitions for converting these data types, because you need to use Uses_Conversion; macro, call the _alloc application and automatically release the resources required. To this end, you don't have to worry about the memory maintenance problem: A2BSTR OLE2A T2A W2A A2COLE2BSTR T2BSTR W2BSTR A2CT OLE2CA T2CA W2CA A2CW OLE2CT T2COL W2COL A2OL OLE2CW T2CW W2CT A2T OLE2T T2OL W2OLELED A2W OLE2W T2W W2T

Or you can use the two functions that cannot be mentioned in the MSDN to implement strings to BSTR conversion

// Use the / GR or / GZ compilation switch, or contain a comsupp.lib, it will be done. #Include int main () {char SZ [] = "Hello"; _BSTR_T B; B = _COM_UTIL :: ConvertStringTOBSTR SZ); char * p = _com_util :: convertBSTRTSTRING (B); Return 1;}

转载请注明原文地址:https://www.9cbs.com/read-962.html

New Post(0)