usage of smart pointers when automating visual studio - c++

I am using below code to manipulate visual studio.
Everything worked fine except that smart pointers did not release properly before function exit: it threw exception upon release.:exception 0xc0000005, access violation when write to 0xfeeefeee.
the running stop at the bold part below.
public:
typedef T _PtrClass;
~CComPtrBase() throw()
{
if (p)
p->Release();
}
Could any one give me some hint?
int myAutomateVS()
{
CoInitialize(NULL);
CComPtr<IRunningObjectTable> pTable=NULL;
GetRunningObjectTable(0, &pTable);
CComPtr<IEnumMoniker> pEnumMoniker=NULL;;
pTable->EnumRunning(&pEnumMoniker);
CComPtr<IMoniker> pMoniker=NULL;
ULONG nMoniker=0;
CComPtr<IUnknown> pRunningObj=NULL;
while(pEnumMoniker->Next(1, &pMoniker, &nMoniker) == S_OK)
{
CComPtr<IBindCtx> pCtx=NULL;
CreateBindCtx(0, &pCtx);
LPOLESTR pwszName;
pMoniker->GetDisplayName(pCtx, NULL, &pwszName);
pTable->GetObject(pMoniker, &pRunningObj);
if(_tcsstr(pwszName, L"VisualStudio.DTE.8") != NULL)
break;
}
CComPtr<EnvDTE::_DTE> pDTE;
pDTE = pRunningObj;
CComPtr<EnvDTE::_Solution> solution;
pDTE->get_Solution(&solution);
CComBSTR fullName;
solution->get_FullName(&fullName);
CoUninitialize();
return 0;
}

Related

IGlobalInterfaceTable::RegisterInterfaceInGlobal returns E_NOTIMPL

Does anyone know why IGlobalInterfaceTable::RegisterInterfaceInGlobal might return E_NOTIMPL?
I'm using ATL's CComGITPtr and simply assigning it to a COM pointer. The assignment, in turn, calls the following ATL code:
HRESULT Attach(_In_ T* p) throw()
{
if (p)
{
CComPtr<IGlobalInterfaceTable> spGIT;
HRESULT hr = E_FAIL;
hr = AtlGetGITPtr(&spGIT);
ATLASSERT(spGIT != NULL);
ATLASSERT(SUCCEEDED(hr));
if (FAILED(hr))
return hr;
if (m_dwCookie != 0)
hr = spGIT->RevokeInterfaceFromGlobal(m_dwCookie);
if (FAILED(hr))
return hr;
return spGIT->RegisterInterfaceInGlobal(p, __uuidof(T), &m_dwCookie);
}
else
{
return Revoke();
}
}
Apparently that last call to spGIT->RegisterInterfaceInGlobal results in E_NOTIMPL.
I'm performing the assignment in the context of an in-proc Explorer extension, and I'm doing it on the main UI thread.
Also, I'm not sure if this is related, but I get the same error when trying to use RoGetAgileReference (on Windows 8.1), doing something like this (with an IShellItemArray):
HRESULT hr;
CComPtr<IAgileReference> par;
hr = RoGetAgileReference(AGILEREFERENCE_DEFAULT, IID_IShellItemArray, psia, &par);
Any ideas what might be going wrong?

Windows Firewall C++ API - How to correctly clean up the COM resources?

I am trying to use the COM-based Windows Firewall API for traversing the existing Firewall rules and find out if one specific rule exists among them.
Currently I have difficulties with understanding what is going on in the Cleanup part of this example (https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ics/c-enumerating-firewall-rules):
/********************************************************************++
Copyright (C) Microsoft. All Rights Reserved.
Abstract:
This C++ file includes sample code for enumerating Windows Firewall
rules using the Microsoft Windows Firewall APIs.
********************************************************************/
#include <windows.h>
#include <stdio.h>
#include <comutil.h>
#include <atlcomcli.h>
#include <netfw.h>
#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )
#define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP"
#define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP"
#define NET_FW_RULE_DIR_IN_NAME L"In"
#define NET_FW_RULE_DIR_OUT_NAME L"Out"
#define NET_FW_RULE_ACTION_BLOCK_NAME L"Block"
#define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow"
#define NET_FW_RULE_ENABLE_IN_NAME L"TRUE"
#define NET_FW_RULE_DISABLE_IN_NAME L"FALSE"
// Forward declarations
void DumpFWRulesInCollection(INetFwRule* FwRule);
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);
int __cdecl main()
{
HRESULT hrComInit = S_OK;
HRESULT hr = S_OK;
ULONG cFetched = 0;
CComVariant var;
IUnknown *pEnumerator;
IEnumVARIANT* pVariant = NULL;
INetFwPolicy2 *pNetFwPolicy2 = NULL;
INetFwRules *pFwRules = NULL;
INetFwRule *pFwRule = NULL;
long fwRuleCount;
// Initialize COM.
hrComInit = CoInitializeEx(
0,
COINIT_APARTMENTTHREADED
);
// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
// initialized with a different mode. Since we don't care what the mode is,
// we'll just use the existing mode.
if (hrComInit != RPC_E_CHANGED_MODE)
{
if (FAILED(hrComInit))
{
wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit);
goto Cleanup;
}
}
// Retrieve INetFwPolicy2
hr = WFCOMInitialize(&pNetFwPolicy2);
if (FAILED(hr))
{
goto Cleanup;
}
// Retrieve INetFwRules
hr = pNetFwPolicy2->get_Rules(&pFwRules);
if (FAILED(hr))
{
wprintf(L"get_Rules failed: 0x%08lx\n", hr);
goto Cleanup;
}
// Obtain the number of Firewall rules
hr = pFwRules->get_Count(&fwRuleCount);
if (FAILED(hr))
{
wprintf(L"get_Count failed: 0x%08lx\n", hr);
goto Cleanup;
}
wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount);
// Iterate through all of the rules in pFwRules
pFwRules->get__NewEnum(&pEnumerator);
if(pEnumerator)
{
hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &pVariant);
}
while(SUCCEEDED(hr) && hr != S_FALSE)
{
var.Clear();
hr = pVariant->Next(1, &var, &cFetched);
if (S_FALSE != hr)
{
if (SUCCEEDED(hr))
{
hr = var.ChangeType(VT_DISPATCH);
}
if (SUCCEEDED(hr))
{
hr = (V_DISPATCH(&var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast<void**>(&pFwRule));
}
if (SUCCEEDED(hr))
{
// Output the properties of this rule
DumpFWRulesInCollection(pFwRule);
}
}
}
Cleanup:
// Release pFwRule
if (pFwRule != NULL)
{
pFwRule->Release();
}
// Release INetFwPolicy2
if (pNetFwPolicy2 != NULL)
{
pNetFwPolicy2->Release();
}
// Uninitialize COM.
if (SUCCEEDED(hrComInit))
{
CoUninitialize();
}
return 0;
}
// Output properties of a Firewall rule
void DumpFWRulesInCollection(INetFwRule* FwRule)
{
variant_t InterfaceArray;
variant_t InterfaceString;
VARIANT_BOOL bEnabled;
BSTR bstrVal;
long lVal = 0;
long lProfileBitmask = 0;
NET_FW_RULE_DIRECTION fwDirection;
NET_FW_ACTION fwAction;
struct ProfileMapElement
{
NET_FW_PROFILE_TYPE2 Id;
LPCWSTR Name;
};
ProfileMapElement ProfileMap[3];
ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN;
ProfileMap[0].Name = L"Domain";
ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE;
ProfileMap[1].Name = L"Private";
ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC;
ProfileMap[2].Name = L"Public";
wprintf(L"---------------------------------------------\n");
if (SUCCEEDED(FwRule->get_Name(&bstrVal)))
{
wprintf(L"Name: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_Description(&bstrVal)))
{
wprintf(L"Description: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_ApplicationName(&bstrVal)))
{
wprintf(L"Application Name: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_ServiceName(&bstrVal)))
{
wprintf(L"Service Name: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_Protocol(&lVal)))
{
switch(lVal)
{
case NET_FW_IP_PROTOCOL_TCP:
wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_TCP_NAME);
break;
case NET_FW_IP_PROTOCOL_UDP:
wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_UDP_NAME);
break;
default:
break;
}
if(lVal != NET_FW_IP_VERSION_V4 && lVal != NET_FW_IP_VERSION_V6)
{
if (SUCCEEDED(FwRule->get_LocalPorts(&bstrVal)))
{
wprintf(L"Local Ports: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_RemotePorts(&bstrVal)))
{
wprintf(L"Remote Ports: %s\n", bstrVal);
}
}
else
{
if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&bstrVal)))
{
wprintf(L"ICMP TypeCode: %s\n", bstrVal);
}
}
}
if (SUCCEEDED(FwRule->get_LocalAddresses(&bstrVal)))
{
wprintf(L"LocalAddresses: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_RemoteAddresses(&bstrVal)))
{
wprintf(L"RemoteAddresses: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_Profiles(&lProfileBitmask)))
{
// The returned bitmask can have more than 1 bit set if multiple profiles
// are active or current at the same time
for (int i=0; i<3; i++)
{
if ( lProfileBitmask & ProfileMap[i].Id )
{
wprintf(L"Profile: %s\n", ProfileMap[i].Name);
}
}
}
if (SUCCEEDED(FwRule->get_Direction(&fwDirection)))
{
switch(fwDirection)
{
case NET_FW_RULE_DIR_IN:
wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_IN_NAME);
break;
case NET_FW_RULE_DIR_OUT:
wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_OUT_NAME);
break;
default:
break;
}
}
if (SUCCEEDED(FwRule->get_Action(&fwAction)))
{
switch(fwAction)
{
case NET_FW_ACTION_BLOCK:
wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_BLOCK_NAME);
break;
case NET_FW_ACTION_ALLOW:
wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_ALLOW_NAME);
break;
default:
break;
}
}
if (SUCCEEDED(FwRule->get_Interfaces(&InterfaceArray)))
{
if(InterfaceArray.vt != VT_EMPTY)
{
SAFEARRAY *pSa = NULL;
pSa = InterfaceArray.parray;
for(long index= pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++)
{
SafeArrayGetElement(pSa, &index, &InterfaceString);
wprintf(L"Interfaces: %s\n", (BSTR)InterfaceString.bstrVal);
}
}
}
if (SUCCEEDED(FwRule->get_InterfaceTypes(&bstrVal)))
{
wprintf(L"Interface Types: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_Enabled(&bEnabled)))
{
if (bEnabled)
{
wprintf(L"Enabled: %s\n", NET_FW_RULE_ENABLE_IN_NAME);
}
else
{
wprintf(L"Enabled: %s\n", NET_FW_RULE_DISABLE_IN_NAME);
}
}
if (SUCCEEDED(FwRule->get_Grouping(&bstrVal)))
{
wprintf(L"Grouping: %s\n", bstrVal);
}
if (SUCCEEDED(FwRule->get_EdgeTraversal(&bEnabled)))
{
if (bEnabled)
{
wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_ENABLE_IN_NAME);
}
else
{
wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_DISABLE_IN_NAME);
}
}
}
// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
HRESULT hr = S_OK;
hr = CoCreateInstance(
__uuidof(NetFwPolicy2),
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(INetFwPolicy2),
(void**)ppNetFwPolicy2);
if (FAILED(hr))
{
wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
goto Cleanup;
}
Cleanup:
return hr;
}
In particular, these lines confuse me:
// Release pFwRule
if (pFwRule != NULL)
{
pFwRule->Release();
}
The pFwRule pointer gets overwritten on each iteration, so here we are explicitly Releaseing only the last Rule that was obtained via QueryInterface in the while loop above.
Releaseing a pointer obtained from a successfull call to QueryInterface is logical, because QueryInterface calls AddRef before returning (which is explicitly stated in the documentation).
But what I cannot understand, is:
Why don't we Release all the previously traversed Rules before querying a next one in the loop? Have they been released implicitly somewhere? Does QueryInterface call Release undercover in case a non-null pointer is passed to it?
Why don't we call Release on pFwRules? Doesn't the INetFwPolicy2::get_Rules function give us a new pointer to a COM object, which is AddRef'ed before being returned to us (and thus must be Released by the caller in the end)?
The same question about the pEnumerator pointer obtained from get__NewEnum: why don't we Release this one as well?
The code is indeed leaking COM memory.
Every call to an interface's AddRef() method must have a matching call to its Release() method. ANY function call that outputs an interface pointer must call AddRef() on it before exit, and the caller must then call Release() on it afterwards.
The general rule is, for any function that allocates and returns memory to the caller, the caller must free it when done using it.
So, to answer your questions:
Yes, there are missing calls to Release() in this code, so there are COM interfaces being leaked - specifically: pFwRules, pEnumerator, and pFwRule are not being Release()'d properly.
DumpFWRulesInCollection() is also leaking COM memory as well. It is not freeing any of the BSTR strings that are output by FwRule's methods.
And also, when it calls SafeArrayGetElement() in a loop, it is not clearing the InterfaceString on each iteration.
No, QueryInterface() does not implicitly Release() a non-null pointer. Just as SafeArrayGetElement() does not clear the element being written to.
It's a reasonable reaction to be confused when studying the sample code. It does indeed leak resources.
Why don't we Release all the previously traversed Rules before querying a next one in the loop? Have they been released implicitly somewhere? Does QueryInterface call Release undercover in case a non-null pointer is passed to it?
No. QueryInterface unconditionally overwrites the value pointed to by its ppvObject argument, either with a NULL pointer, if the COM object does not implement the requested interface, or with a pointer to the requested interface. Not calling Release is a resource leak.
Why don't we call Release on pFwRules? Doesn't the INetFwPolicy2::get_Rules function give us a new pointer to a COM object, which is AddRef'ed before being returned to us (and thus must be Released by the caller in the end)?
Correct again. get_Rules returns a resource the caller is responsible for. Not calling Release on the returned interface is a resource leak.
The same question about the pEnumerator pointer obtained from get__NewEnum: why don't we Release this one as well?
The same rules apply here as well: The caller is responsible for cleaning up the iterator it received. This, too, is a resource leak.
Special note on MSDN samples: Although they are tagged "C++", the majority of code samples for COM are actually written in C. Unlike C++, C doesn't have much to offer with respect to automatic resource management.
If you are using C++, you can take advantage of automatic resource management, and employ one of the provided smart pointer types (e.g. ATL's CComPtr, or Visual C++' _com_ptr_t).

Problems accessing a COM interface in C++

What I want to do is access a COM interface and then call the "Open" method of that interface.
I have a sample code in Visual Basic which works fine, but I need to write it in C++ and I can't seem to get it to work.
First of all, this is the working VB code:
Dim CANapeApplication As CANAPELib.Application
CANapeApplication = CreateObject("CANape.Application")
Call CANapeApplication.Open("C:\Users\Public\Documents\Vector\CANape\12\Project", 0)
CANape.Application is the ProgID which selects the interface I need.
After reading some docs at msdn.microsoft.com and this question, I wrote this code:
void ErrorDescription(HRESULT hr); //Function to output a readable hr error
int InitCOM();
int OpenCANape();
// Declarations of variables used.
HRESULT hresult;
void **canApeAppPtr;
IDispatch *pdisp;
CLSID ClassID;
DISPID FAR dispid;
UINT nArgErr;
OLECHAR FAR* canApeWorkingDirectory = L"C:\\Users\\Public\\Documents\\Vector\\CANape\\12\\Project";
int main(){
// Instantiate CANape COM interface
if (InitCOM() != 0) {
std::cout << "init error";
return 1;
}
// Open CANape
if (OpenCANape() != 0) {
std::cout << "Failed to open CANape Project" << std::endl;
return 1;
}
CoUninitialize();
return 0;
}
void ErrorDescription(HRESULT hr) {
if(FACILITY_WINDOWS == HRESULT_FACILITY(hr))
hr = HRESULT_CODE(hr);
TCHAR* szErrMsg;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&szErrMsg, 0, NULL) != 0)
{
_tprintf(TEXT("%s"), szErrMsg);
LocalFree(szErrMsg);
} else
_tprintf( TEXT("[Could not find a description for error # %#x.]\n"), hr);
}
int InitCOM() {
// Initialize OLE DLLs.
hresult = OleInitialize(NULL);
if (!SUCCEEDED(hresult)) {
ErrorDescription(hresult);
return 1;
}
// Get CLSID from ProgID
//hresult = CLSIDFromProgID(OLESTR("CANape.Application"), &ClassID);
hresult = CLSIDFromProgID(OLESTR("CanapeCom.CanapeCom"), &ClassID);
if (!SUCCEEDED(hresult)) {
ErrorDescription(hresult);
return 1;
}
// OLE function CoCreateInstance starts application using GUID/CLSID
hresult = CoCreateInstance(ClassID, NULL, CLSCTX_LOCAL_SERVER,
IID_IDispatch, (void **)&pdisp);
if (!SUCCEEDED(hresult)) {
ErrorDescription(hresult);
return 1;
}
// Call QueryInterface to see if object supports IDispatch
hresult = pdisp->QueryInterface(IID_IDispatch, (void **)&pdisp);
if (!SUCCEEDED(hresult)) {
ErrorDescription(hresult);
return 1;
}
std::cout << "success" << std::endl;
return 0;
}
int OpenCANape() {
//Method name
OLECHAR *szMember = L"Open";
// Retrieve the dispatch identifier for the Open method
// Use defaults where possible
DISPID idFileExists;
hresult = pdisp->GetIDsOfNames(
IID_NULL,
&szMember,
1,
LOCALE_SYSTEM_DEFAULT,
&idFileExists);
if (!SUCCEEDED(hresult)) {
std::cout << "GetIDsOfNames: ";
ErrorDescription(hresult);
return 1;
}
unsigned int puArgErr = 0;
VARIANT VarResult;
VariantInit(&VarResult);
DISPPARAMS pParams;
memset(&pParams, 0, sizeof(DISPPARAMS));
pParams.cArgs = 2;
VARIANT Arguments[2];
VariantInit(&Arguments[0]);
pParams.rgvarg = Arguments;
pParams.cNamedArgs = 0;
pParams.rgvarg[0].vt = VT_BSTR;
pParams.rgvarg[0].bstrVal = SysAllocString(canApeWorkingDirectory);
pParams.rgvarg[1].vt = VT_INT;
pParams.rgvarg[1].intVal = 0; // debug mode
// Invoke the method. Use defaults where possible.
hresult = pdisp->Invoke(
dispid,
IID_NULL,
LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD,
&pParams,
&VarResult,
NULL,
&puArgErr
);
SysFreeString(pParams.rgvarg[0].bstrVal);
if (!SUCCEEDED(hresult)) {
ErrorDescription(hresult);
return 1;
}
return 0;
}
There are several problems with this.
Using the ClassID received from CLSIDFromProgID as the first parameter of CoCreateInstance does not work, it returns the error: class not registered
If i use the ProgID CanapeCom.CanapeCom (I found it by looking in the Registry), CoCreateInstance works. However, when I use pdisp->GetIDsOfNames I get the error message: Unkown name. Which I think means that the method was not found. That seems logical because I've used a different ProgID, but I just can't figure out how to get to the interface I'm looking for.
I have also tried to use the resulting CLSID from CLSIDFromProgID(OLESTR("CANape.Application"), &ClassID); as the 4th argument of CoCreateInstance but that resulted in a "No such interface supported" error.
Do I need the dll file of the software? In the VB example the dll file is used to get the interface and then create a new object using the ProgID. I'm not sure if I need to do the same in C++ or how this should work.
I'm really stuck here and hope that someone can help me.
Thanks for your comments.
I've fixed the problem, although the solution is kind of embarrassing...
In my defense, I'm still a student and new to this kind of stuff.
I've used the Process Monitor to check what happens when I execute the VB script.
I saw that the CLSID used there is the ID returned by CLSIDFromProgID(OLESTR("CANape.Application"), &ClassID);, which meant that this had to be the right one and the problem had to be somewhere else. I've looked again at the CoCreateInstance and then took a look at the other parameters. Turns out that the context CLSCTX_LOCAL_SERVER was wrong, it has to be CLSCTX_INPROC_SERVER. I don't know why I've set it to local_server in the first place or why I've never questioned it. I wrote that part of the code a few days ago and then focused too much on the CLSID and IID rather than on the other parameters.
I've also taken the first comment from Alex into account and created a tlb file.
This is a simplified version of the code that works:
#import "CANape.tlb"
int _tmain(int argc, _TCHAR* argv[])
{
_bstr_t path = "C:\\Users\\Public\\Documents\\Vector\\CANape\\12\\Project";
CLSID idbpnt;
CoInitialize(NULL);
HRESULT hr = CLSIDFromProgID (L"CANape.Application", &idbpnt);
CANAPELib::IApplication *app;
hr = CoCreateInstance(idbpnt,NULL,CLSCTX_INPROC_SERVER,__uuidof(CANAPELib::IApplication),(LPVOID*)&app );
app->Open(path,0);
CoUninitialize();
return 0;
}

Why COM doesn't work in a new thread?

My problems started after converting my VS2003 project to VS2008. Solution contains 3 projects. Projects are DLL's. There were A LOT of compilation errors, then some linker errors... Well, I fought them off. Now it just simply doesn't work ;)
So, one of this DLL's is suppoused to communicate with Word by COM.
Word::_ApplicationPtr d_pApp;
Word::_DocumentPtr d_pDoc;
void MSWord2003::init()
{
free();
HRESULT hr;
CLSID clsid;
CLSIDFromProgID(L"Word.Application", &clsid);
// Get an interface to the running instance, if any..
IUnknown *pUnk;
hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);
if(hr!=S_OK)
throw MSWord::MSWordException("Nie znaleziono działającej aplikacji MSWord.");
IDispatch* d_pDispApp;
hr = pUnk->QueryInterface(IID_IDispatch, (void**)&d_pDispApp);
if(hr!=S_OK)
throw MSWord::MSWordException("Nie udało się połączyć z aplikacją MSWord.");
pUnk->Release();
pUnk = 0;
d_pApp = d_pDispApp;
d_pDoc = d_pApp->ActiveDocument;
d_pDispApp->AddRef();
d_currIdx = -1;
paragraphsCount = d_pDoc->GetParagraphs()->Count;
footnotesCount = d_pDoc->GetFootnotes()->Count;
endnotesCount = d_pDoc->GetEndnotes()->Count;
}
void MSWord2003::free()
{
if(d_pApp!=0)
{
d_pApp->Release();
d_pApp=0;
}
}
This code works on VS2003 (and different machine, I don't have VS2003 on my computer) while in VS2008 it works only if it is called by main thread.
When called by a new thread (wich is initialized by CoInitialize) d_pApp is not initialized properly - its ptr shows 0.
While debugging I reached code in comip.h:
template<typename _InterfacePtr> HRESULT _QueryInterface(_InterfacePtr p) throw()
{
HRESULT hr;
// Can't QI NULL
//
if (p != NULL) {
// Query for this interface
//
Interface* pInterface;
hr = p->QueryInterface(GetIID(), reinterpret_cast<void**>(&pInterface));
// Save the interface without AddRef()ing.
//
Attach(SUCCEEDED(hr)? pInterface: NULL);
}
else {
operator=(static_cast<Interface*>(NULL));
hr = E_NOINTERFACE;
}
return hr;
}
In a new thread, QueryInterface returns E_NOINTERFACE, although GetIID() returns the same thing for both threads. And that is where I got stuck - I have no idea, what causes this behaviour...
IMO you should initialize COM not with CoInitialize, but with CoInitializeEx, specifying COINIT_MULTITHREADED. Otherwise you'll have separate single-threaded COM apartment for every thread.

Do I have to use ->Release()?

I am working with a webbrowser host on c++, I managed to sink event and I am running this void on DISPID_DOCUMENTCOMPLETE:
void DocumentComplete(LPDISPATCH pDisp, VARIANT *url)
{
READYSTATE rState;
iBrowser->get_ReadyState(&rState);
if(rState == READYSTATE_COMPLETE)
{
HRESULT hr;
IDispatch *pHtmlDoc = NULL;
IHTMLDocument2 *pDocument = NULL;
IHTMLElement *pBody = NULL;
IHTMLElement *lpParentElm = NULL;
BSTR bstrHTMLText;
hr = iBrowser->get_Document(&pHtmlDoc);
hr = pHtmlDoc->QueryInterface(IID_IHTMLDocument2, (void**)&pDocument);
if( (FAILED(hr)) || !pDocument)
{
MessageBox(NULL, "QueryInterface failed", "WebBrowser", MB_OK);
}
hr = pDocument->get_body( &pBody );
if( (!SUCCEEDED(hr)) || !pBody)
{
MessageBox(NULL, "get_body failed", "WebBrowser", MB_OK);
}
pBody->get_parentElement(&lpParentElm);
lpParentElm->get_outerHTML(&bstrHTMLText);
_bstr_t bstr_t(bstrHTMLText);
std::string sTemp(bstr_t);
MessageBox(NULL, sTemp.c_str(), "WebBrowser", MB_OK);
}
}
I don't much about c++, I built this code from watching other codes in google. Now I know I have to use ->Release, but do I have to use all these?:
pHtmlDoc->Release();
pDocument->Release();
pBody->Release();
lpParentElm->Release();
iBrowser->Release();
Because on the examples I used to build my code it was using it only for the IHTMLElement(s).
Yes, you do have to call Release() on those pointers, otherwise objects will leak. The same goes for BSTRs.
You'll be much better off if you use smart pointers for that - ATL::CComPtr/ATL::CComBSTR or _com_ptr_t/_bstr_t.
You should wrap those objects into a CComPtr or one of its variants. That will handle the release for you. It goes with the concept of RAII.
Yes you do. But not on the iBrowser, you didn't acquire that pointer inside this code.
Beware that your error checking isn't sufficient, your code will bomb when get_Document() fails. Same for get_parentElement(). And after the message box is dismissed.