This test case worked without any problems for me whether or not the class derived from COleSafeArray loaded the SAFEARRAY in the constructor or in a subsequent function call after construction.
class Object {
public:
Object() = default;
~Object() = default;
CString* getArray()
{
return m_arr;
}
int getElements()
{
return ARRAYSIZE(m_arr);
}
CString m_arr[5]{ L"one", L"two", L"three", L"four", L"five" };
};
class CWrapOle : public COleSafeArray
{
public:
CWrapOle(Object* obj, bool bLoad) : m_bLoad(bLoad)
{
DWORD dwElements = obj->getElements();
Create(VT_BSTR, 1, &dwElements);
if (bLoad)
{
long ndx[1]{};
CString* pArray = obj->getArray();
for (DWORD i = 0; i < dwElements; i++)
{
ndx[0] = i;
PutElement(ndx, CComBSTR(pArray[i]));
}
}
}
void LoadArray(Object* obj)
{
if (!m_bLoad)
{
long lBound{MAXLONG}, uBound{MAXLONG};
DWORD dwElements = obj->getElements();
GetLBound(1, &lBound);
GetUBound(1, &uBound);
ASSERT(dwElements == uBound - lBound + 1);
long ndx[1]{};
CString* pArray = obj->getArray();
for (DWORD i = 0; i < dwElements; i++)
{
ndx[0] = i;
PutElement(ndx, CComBSTR(pArray[i]));
}
}
}
private:
bool m_bLoad{ false };
};
If you want to load the array in the derived class constructor pass "true", otherwase pass "false".