views:

7

answers:

1

I'm develop a VC Add-In for VC6 and VC9. The following codes are from my works. In CViaDevStudio::Evaluate, after I call pDebugger->Release() and it's all OK. But in CViaVisualStudio::ReadFromMemory, after I call pDebugger->Release() or pProc->Release(), VC9 will prompt a error complaint a unspecified error number. I don't know why. I think it's reasonable to call Release() after I have used a COM object.

/* VC6 */
class CViaDevStudio {
...
IApplication* m_pApplication;
};

BOOL    CViaDevStudio::Evaluate(char* szExp, TCHAR* value, int size)
{
    BOOL re = FALSE;
    IDebugger*  pDebugger = NULL;
    m_pApplication->get_Debugger((IDispatch**)&pDebugger);

    if (pDebugger) {
        ...
    }

exit:
        // The following code must be called, otherwise VC6 will complaint invalid access
        // when it's started again
    if (pDebugger)
        pDebugger->Release();

    return re;
}    

/* VC9 */
class     CViaVisualStudio {
    ...
    CComPtr<EnvDTE::_DTE> m_pApplication;
};

BOOL    CViaVisualStudio::ReadFromMemory(PBYTE pDst, PBYTE pSrc, long size)
{
    BOOL re = FALSE;
    EnvDTE::DebuggerPtr pDebugger;
    EnvDTE::ProcessPtr pProc;

    if (S_OK == m_pApplication->get_Debugger(&pDebugger)) {
        if (S_OK == pDebugger->get_CurrentProcess(&pProc)) {
            ...
            }
        }
    }

exit:
    // I don't know why the following enclosed with macros should not be called.
#if 0
    if (pDebugger)
        pDebugger->Release();
    if (pProc)
        pProc->Release();
#endif
    return re;
}
+2  A: 
EnvDTE::DebuggerPtr pDebugger;

Note how the declaration of the pointer is different from the way you did it in Evaluate. It is an IDebugger* there. The DebuggerPtr class is a wrapper class generated by the #import directive. It is a smart pointer class, it knows how to call Release() automatically. Even if the code throws exceptions, it won't leak the pointer. Highly recommended. You'll find it documented in the MSDN library as the _com_ptr_t class.

Hans Passant
Thanks very much!
Cook Schelling