我正在尝试(i)在 COM 边界上获取一个 longs 的安全数组,以及(ii)为方便起见使用 CComSafeArray。
我的问题是在设置 COM 属性后我遇到了不可预知的崩溃(请参阅下面的pPrologue->EligibleProducts = var;)。我发现很难从 Microsoft 文档中理解如何使用 CComSafeArray,任何人都可以解释一下吗?先感谢您!
在 IDL 我有:
[propget, id(1), helpstring("property EligibleProducts")] HRESULT EligibleProducts([out, retval] VARIANT* pVal);
[propput, id(1), helpstring("property EligibleProducts")] HRESULT EligibleProducts([in] VARIANT newVal);
我的服务器代码是:
STDMETHODIMP CPrologue::put_EligibleProducts(VARIANT newVal)
{
HRESULT hr = E_FAIL;
AFX_MANAGE_STATE(AfxGetStaticModuleState())
//start by clearing out any existing data
m_EligibleProducts.clear();
if(newVal.vt | (VT_ARRAY & VT_I4))
{
//construct a wrapper class with the passed in SAFEARRAY
CComSafeArray<long> wrapper;
wrapper.Attach(newVal.parray);
int iProductID = 0;
//loop through products and add them to our vector
int iCount = wrapper.GetCount();
for(int iIndex = 0; iIndex < iCount; iIndex++)
{
iProductID = wrapper.GetAt(iIndex);
if(iProductID > 0)
{
m_EligibleProducts.push_back(iProductID);
}
}
hr = S_OK;
return hr;
}
我的调用代码是:
VARIANT var;
::VariantInit(&var);
var.vt = VT_ARRAY | VT_I4;
CComSafeArray<long> wrapper;
for(std::vector<long>::const_iterator it = products.begin(); it != products.end(); it++)
{
wrapper.Add(*it);
}
//get the SAFEARRAY from the wrapper
var.parray = wrapper.Detach();
//and store it on the appropriate business object
IProloguePtr pPrologue = pCustomer->Prologue;
**pPrologue->EligibleProducts = var;**
//clean up the variant (and hence SAFEARRAY)
::VariantClear(&var);