BSTR详解三 - BSTR使用注意事项2007-9-7 21:34:12
1.1 BSTR分析 BSTR设计对于C++程序员好坏参半。 1.2 BSTR使用基本规则
1.3 BSTR参数使用 多数时候,BSTR是被用于函数参数。关于BSTR参数的使用规则是BSTR类型的基础。只有熟练掌握,才能分析warpper类或转换函数的正确性。 基本原则:在给by-reference[in/out]参数赋一个新的值前,被调用者负责释放。其他情况,都是调用者负责释放。 调用者使用BSTR的规则如下: · 释放被调用函数返回的BSTR,或者被调用函数通过by-reference返回的BSTR。 HRESULT IWebBrowser2::get_StatusText( BSTR FAR* pbstr ); //... BSTR bstrStatus; pBrowser->get_StatusText( &bstrStatus ); // shows using the Win32 function // to freee the memory for the string: ::SysFreeString( bstrStatus ); · 释放通过by-value方式传给其他函数的BSTR. //.h HRESULT IWebBrowser2::put_StatusText( BSTR bstr ); //.cpp // shows using the Win32 function // to allocate memory for the string: BSTR bstrStatus = ::SysAllocString( L"Some text" ); if (bstrStatus == NULL) return E_OUTOFMEMORY; pBrowser->put_StatusText( bstrStatus ); // Free the string: ::SysFreeString( bstrStatus ); //... 被调用者按照如下规则处理BSTR: · 如果一个BSTR参数是by-reference方式,在给参数赋新值之前,Free以前的值。如果没有给参数赋的新值,不要Free传入值。 void RefreshBSTR(BSTR& bs) // bs is an [in/out] parameter. BSTR* is the same { // using the bs here Dosomething(bs); // if (bs is about to be updated) ASSERT(bs != NULL); ::SysReallocString(bs, _T(“NEW STRING”)); // SysReallocString will call SysFreeString and // SysAllocString in sequence // If bs is only [out] parameter, SysAllocString // should be called here. } · 不要Free通过by-value传入的BSTR。 void SetBSTR(BSTR bs) // bs is an [in] parameter. BSTR* is the same { // using the bs here Dosomething(bs); ::SysFreeString(bs); //ERROR } · 不要Free返回给调用者的 BSTR . BSTR GetBSTR1() { BSTR bs = ::SysAllocString(_T(“test”)); ::SysFreeString(bs); //ERROR return bs; } void GetBSTR2(BSTR* pBs) { CComBSTR bs(_T(“test”)); *pBS = (BSTR) bs; //ERROR: pBS will be freed automatically } · 如果需要保存传入的BSTR,被调用着需要用SysAllocString()生成一个新的副本,并保存。输入的BSTR会被调用者释放。 void MyClass::SetBSTR(BSTR bs) { //BSTR m_bs; m_bs = bs; //ERROR m_bs = ::SysReAllocString(bs); } · 如果需要返回一个已经存储的BSTR,返回BSTR的一个拷贝。调用者释放返回的BSTR拷贝。 void MyClass::GetBSTR(BSTR* pbs) { //BSTR m_bs; *pbs = m_bs; //ERROR *pbs = ::SysAllocString(m_bs); } |
|
|