Click to See Complete Forum and Search --> : Clarifications on COM programming


vprabha123
April 24th, 2003, 07:54 AM
Hi ,

Can anyone clarify each of the following situations :

A.dll and B.dll mentioned below are ATL/COM dlls developed using VC++ 6.0

1. We have a ATL/COM dll say A.dll instantiating another ATL/COM dll B.dll using CoCreateInstance. Once A.dll has completed using the methods of B.dll , should we do a
B_ptr->Release() in the code of A.dll to avoid memory leaks ?

2. A.dll is instantiating the Microsoft's MSXML Parser 3.0 dll . We have the following variables declared in A.dll.

MSXML2::IXMLDOMDocument* mv_iXMLDoc;
MSXML2::IXMLDOMElement* mv_iXMLElm;
MSXML2::IXMLDOMNode* mv_iXMLNode;
MSXML2::IXMLDOMNodeList* mv_iXMLNodeList;

mv_iXMLDoc gets populated using CoCreateInstance. mv_iXMLElm , mv_iXMLNode , mv_iXMLNodeList are all populated using the MSXML Parser methods. Once the use of these pointers is over , should each of these pointers be released to avoid memory leaks ?

3. The mv_iXMLNode in question 2 is assigned as
mv_iXMLNodeList->nextNode(&mv_iXMLNode);
inside a while loop .
Should mv_iXMLNode be released of memory everytime before its gets a new value from the mv_iXMLNodeList?

4. If for question 2 and 3 , the pointers should be freed of the memory once its use is over , then what is the function used to free the pointers?

5. Can anyone suggest sites which gives C++ code samples for MSXML parser 3.0 ? Most of the examples I have come across are Visual Basic code .

Regards
Prabha

fellowDeveloper
April 24th, 2003, 01:47 PM
1. Yes, you must do a B_ptr->Release() to avoid memory leaks.

However, I like to use the ATL smart pointer CComPtr because it manages your COM interface pointers for you. For instance, it automatically releases the encapsulated interface pointer for you in its destructor. If you don't want to use ATL, use the compiler COM support smart pointer _com_ptr_t, it works just as well.

2. Same situation as 1.

3. Yes, make sure you do a mv_iXMLNode->Release() everytime before it gets a new value. Something like:


while(mv_iXMLNodeList->nextNode(&mv_iXMLNode) == S_OK)
{
// Other code here...
mv_iXMLNode->Release();
mv_iXMLNode = NULL;
}

// Or if using the smart pointer CComPtr,

while(mv_iXMLNodeList->nextNode(&mv_iXMLNode) == S_OK)
{
// Other code here...
mv_iXMLNode.Release();
}


The reason you have to do an explicit Release here is because you are reusing the same smart pointer object.

4. Since the IXML* interfaces are derived from IDispatch, you use the function Release to free the pointer.