Sunday, July 20, 2014

Memory management of BSTR objects in COM

When working with BSTR with COM objects, the following questions have to be answered:
1. When passing BSTR to a COM object, who is responsible to free the memory allocated to BSTR?
2. When a COM object returns BSTR, who is responsible to free the memory allocated to BSTR?

Answer to both these questions is: caller of the COM object is responsible for freeing memory allocated to BSTR.

Examples:
1. When passing BSTR to COM object
Solution:
    {
            CComPtr<IComDog> dog;
            dog.CoCreateInstance(Animals::CLSID_Dog);
            BSTR nameOfDog = SysAllocString(L"Tiger");
            dog->put_NameOfDog(nameOfDog);
            .....
            // other code for dogs
            .....
            SysFreeString(nameOfDog);
            nameOfDog = NULL;
    }

Instead of using BSTR directly, use CComBSTR which takes care of memory management.
    {
            CComPtr<IComDog> dog;
            dog.CoCreateInstance(Animals::CLSID_Dog);
            CComBSTR nameOfDog = L"Tiger";
            dog->put_Name(nameOfDog);
            .....
            // other code for dogs
            // free'ing memory allocated to nameOfDog is taken care of by CComPtr
     }

2. When COM return a BSTR
     TBD

No comments:

Post a Comment