Link to home
Start Free TrialLog in
Avatar of kutruta
kutruta

asked on

CoInitializeEx problem

I have a simple COM object dll

skeletal description ...

class ATL_NO_VTABLE Cxxx :
public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<Cxxx,
&CLSID_Cxxx>,
public Ixxx
{
public:
DECLARE_REGISTRY_RESOURCEID(IDR_xxx)
DECLARE_NOT_AGGREGATABLE(Cxxx)
DECLARE_PROTECT_FINAL_CONSTRUCT()

BEGIN_COM_MAP(Cxxx)
COM_INTERFACE_ENTRY(Ixxx)
END_COM_MAP()

STDMETHOD(AddNumbers)(/*[in]*/ long Num1, /*[in]*/ long Num2, /*[out]*/ long *ReturnVal);
};

with this simple IDL interface ..

interface Ixxx : IUnknown
{
[helpstring("method AddNumbers")]
HRESULT AddNumbers([in] long Num1, [in] long Num2, [out] long *ReturnVal);
};


I can SUCCESSFULLY use the dll from a C++ snippet, by using CoInitializeEx or CoInitialize, like this

.
.

#define _WIN32_DCOM

#import "..\xxx.dll" no_namespace
#include "..\xxx_i.c"
.
.

HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED |
COINIT_DISABLE_OLE1DDE |
COINIT_SPEED_OVER_MEMORY);

// OR . . .HRESULT hr = CoInitialize(NULL);

if(SUCCEEDED(hr))
{
Ixxx*     ixxx;
long x;
char temp[20];

hr = CoCreateInstance(CLSID_xxx,
NULL,
CLSCTX_ALL,
IID_Ixxx, (void**) &ixxx);
     
if(SUCCEEDED(hr))
{
hr = ixxx->AddNumbers(5, 6, &x);
hr = ixxx->Release();
::MessageBox(NULL, ltoa(x, temp, 10), "", MB_OK);
}
}
CoUnInitialize();
.
.
.

But when I use CoInitializeEx in the way I wish to,  (multithreaded) like this:


HRESULT hr = CoInitializeEx(NULL,
COINIT_MULTITHREADED |
COINIT_DISABLE_OLE1DDE |
COINIT_SPEED_OVER_MEMORY);


the CoCreateInstance fails.

Why is COINIT_MULTITHREADED causing this?

best regards .....

Avatar of JoeMarshall
JoeMarshall

is your snippet of code also in a dll or in an MFC app? If so, it may fail because CoInitializeEx has already been called and you are in a Single Threaded Apartment. You can find out if that's so by looking at the return value from the call which worked (with COINIT_APARTMENTTHREADED) and see if that is S_FALSE (which will still pass the SUCCEEDED(hr) test.). If so, that's the case.

If that's so, you're stuck with the apartment you are in.

Joe
ASKER CERTIFIED SOLUTION
Avatar of ee_ai_construct
ee_ai_construct
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial