如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?



我正在使用一个COM对象。我调用 COM 对象的函数,此函数返回包含我的设备列表的安全数组的 VARIANT 数据类型。 我如何使用这个变体来访问我的设备。

VARIANT namList; 
SAFEARRAY* myequip;
namList=str->GetNames();

为了在这样的 VARIANT 中使用 SAFEARRAY,您需要进行大量的验证和错误检查。这是您需要遵循的粗略模式。请仔细阅读评论,因为我对您正在使用的COM API做了一些假设。

// verify that it's an array
if (V_ISARRAY(&namList))
{
// get safe array
LPSAFEARRAY pSafeArray = V_ARRAY(&namList);
// determine the type of item in the array
VARTYPE itemType;
if (SUCCEEDED(SafeArrayGetVartype(pSafeArray, &itemType)))
{
// verify it's the type you expect
// (The API you're using probably returns a safearray of VARIANTs,
// so I'll use VT_VARIANT here. You should double-check this.)
if (itemType == VT_VARIANT)
{
// verify that it's a one-dimensional array
// (The API you're using probably returns a one-dimensional array.)
if (SafeArrayGetDim(pSafeArray) == 1)
{
// determine the upper and lower bounds of the first dimension
LONG lBound;
LONG uBound;
if (SUCCEEDED(SafeArrayGetLBound(pSafeArray, 1, &lBound)) && SUCCEEDED(SafeArrayGetUBound(pSafeArray, 1, &uBound)))
{
// determine the number of items in the array
LONG itemCount = uBound - lBound + 1;
// begin accessing data
LPVOID pData;
if (SUCCEEDED(SafeArrayAccessData(pSafeArray, &pData)))
{
// here you can cast pData to an array (pointer) of the type you expect
// (The API you're using probably returns a safearray of VARIANTs,
// so I'll use VARIANT here. You should double-check this.)
VARIANT* pItems = (VARIANT*)pData;
// use the data here.
// end accessing data
SafeArrayUnaccessData(pSafeArray);
}
}
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新