A BSTR is a pointer to a null-terminated character string in which the string length is stored with the string. Because the length is stored with the string, BSTR variables can contain embedded null characters.

A CString object consists of a variable-length sequence of characters. CString provides functions and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays. CString is the most preferred way of creating a string type of variable in MFC.

While working with COM, you may encounter several occassions, when you need to do interconversion between these two. Many programmers find it difficult, but in fact, it is very easy to do this conversion.

I will show a simple example of string concatenation. Here an interface of a COM Server exposes a method that takes two BSTR and returns a BSTR that is a concatenated version of previous two. At the client side, its the CString that originally contains the individual strings. So a conversion of CString to BSTR will be required while calling the method. Simillary, while displaying the returned value, BSTR to CString conversion will be required.

Following is the sample code for some interface in COM Server.

STDMETHODIMP CSampleClass::SampleConcat(BSTR string1, BSTR string2, BSTR* string3)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());

CString str;
str.Format( _T("%s%s"), string1, string2);
BSTR st = str.AllocSysString();
*string3 = st;

return S_OK;
}

And following is the sample code in client part, that interacts with above method. In following code, m_txtString1 and m_txtString2 are the textboxes and m_lblOutput2 is some static text label.

void CSampleCOMClientDlg::OnBnClickedBtnConcatenate()
{
HRESULT hr;
CString str1, str2;

m_txtString1.GetWindowTextA(str1);
m_txtString2.GetWindowTextA(str2);

BSTR result;

hr = sampleClassPtr->SampleConcat( str1.AllocSysString(),
str2.AllocSysString(), &result);

if( SUCCEEDED(hr) )
{
m_lblOutput2.SetWindowTextA((CString)result);
}
else
{
AfxMessageBox("Error calling the method in COM");
m_lblOutput2.SetWindowTextA("");
}
}

Hence, the interconversion of CString and BSTR is very easy.



No Responses Yet to “BSTR to CString and CString to BSTR Conversion”  

  1. No Comments Yet

Leave a Reply