Tuesday, October 25, 2005

Return a string in COM methods.

In a typical com function which returns a string, people could make an error easily like the following one:

STDMETHODIMP MyClass::MyFunction(BSTR* pRet)
{
// This is how I return a string - is this incorrect?
std::string myString;
CComBSTR bstr (A2W (myString.c_str()));
*pRet = bstr;
return S_OK;
}

Issue with this is : while pRet points to the bstr , but bstr is defined inside the function scope, so when it goes out of the scope, the CComBSTR destructor will be called like this:

~CComBSTR() throw()
{
::SysFreeString(m_str);
}
which now makes pRet point to a dangling pointer.

An appropriate way is detach the m_str from the CComBSTR , so even when the destructor is called, the m_str won't be destroyed.

BSTR Detach() throw()
{
BSTR s = m_str;
m_str = NULL;
return s;
}

No comments: