SAFEARRAY of COM objects

0

I'm using COM library and I have interface defined in .tlh file as following:

_COM_SMARTPTR_TYPEDEF(IMyInterface, __uuidof(IMyInterface));

Then I create object:

//1st object
IMyInterfacePtr pMyInterface1;
pMyInterface1.CreateInstance(CLSID_MyInterface);
pMyInterface1->call_some_method(BSTR("pass example text1"));

//2nd object
IMyInterfacePtr pMyInterface2;
pMyInterface2.CreateInstance(CLSID_MyInterface);
pMyInterface2->call_some_method(BSTR("pass example text2"));

Then I need to create SAFEARRAY of these objects:

SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = 2;
rgsabound[0].lLbound = 0;

SAFEARRAY *pData = SafeArrayCreate(VT_VARIANT, 1, rgsabound);

LONG i = 0;
SafeArrayPutElement(pData, &i, pMyInterface1);
i = 1;
SafeArrayPutElement(pData, &i, pMyInterface2);

But unfortunately after this array elements remains empty. Which is the proper way to fill this array of IMyInterfacePtr objects?

Thank you so much for help.

------EDIT------

Thanks for answers. I tried these solutions from comments, but unfortunately, it still doesn't work. I need to send back this array to COM by COM method. So I'm creating a new object:

IResponsePtr pResponse;//This is also smart com ptr
pResponse.CreateInstance(CLSID_Response);
pResponse->put_Response(pData);//safearray here

where put_Response has following signature: (SAFEARRAY *value). Unfortunately, during calling this method I'm getting the following exception:

First-chance exception at 0x76BEC54F in MyApp.exe: Microsoft C++ exception: EEException at memory location 0x0042F144.
First-chance exception at 0x76BEC54F (KernelBase.dll) in MyApp.exe: 0xE0434352 (parameters: 0x80131533, 0x00000000, 0x00000000, 0x00000000, 0x72D30000).

Any ideas what might be wrong with this SAFEARRAY ptr?

c++
com
safearray
asked on Stack Overflow Nov 14, 2017 by drewpol • edited Nov 14, 2017 by drewpol

1 Answer

3

Don't use the pointers. Store the pointers in the variant first and than copy the data.

VARIANT v;
v.vt = VT_UNKNOWN;
v.punkVal = pMyInterface1;
SafeArrayPutElement(pData, &i, &v);

SafeArrayPutElement uses AddRef internally when it copies the variant.

answered on Stack Overflow Nov 14, 2017 by xMRi • edited Nov 14, 2017 by xMRi

User contributions licensed under CC BY-SA 3.0