C語(yǔ)言_bstr_t和CComBSTR

字號(hào):

bstr_t在VC中是為了兼容BSTR類(lèi)型而增加的,也就是為了實(shí)現(xiàn)LPCSTR與BSTR轉(zhuǎn)換。
    它需要頭文件#include
    bstr_t 是BSTR的包裝類(lèi)
    轉(zhuǎn)換方法
    LPSTR strDemo="Test";
    bstr_t bstr(strDemo);
    建議加上try,catch,用于catch(_com_error &e)
    The following pseudocode shows the typical use of CComBSTR:
    HRESULT CMyObject::MyMethod(IOtherObject* pSomething)
    {
    CComBSTR bstrText(L"Hello");
    bstrText += " again"; // LPCSTR conversion
    bstrText.ToUpper();
    pSomething->Display(bstrText); // [in] parameter
    MessageBoxW(0, bstrText, L"Test", MB_OK); // Assumes Windows NT
    }
    As you can see, CComBSTR significantly simplifies the use of BSTRs. Four uses of CComBSTR, however, require special care:
    Freeing the BSTR explicitly
    Using CComBSTR as an [out] parameter
    Using a CComBSTR automatic variable in right-side assignments
    Using a CComBSTR member variable in right-side assignments
    當(dāng)在BSTR*所在的位置作為一個(gè)[out]參數(shù)傳遞CComBSTR時(shí),你必須先調(diào)用Empty釋放string的內(nèi)容,就象下面這樣:HRESULT CMyObject::MyMethod2(ISomething* p, /*[out]*/ BSTR* pbstr)
    {
    CComBSTR bstrText;
    bstrText = L"Some assignment"; // BSTR is allocated.
    bstrText.Empty(); // Must call empty before
    pSomething->GetText(&bstrText); // using as an [out] parameter.
    if(bstrText != L"Schaller")
    bstrText += "Hello"; // Convert from LPCSTR.
    }
    因?yàn)樵谥貙?xiě)B(tài)STR內(nèi)容之前方法COM 為[out] 參數(shù)的規(guī)則是并不調(diào)用sysfreestring。