繁体   English   中英

如何使用C ++中的COM对象返回的VARIANT数据类型访问SAFE ARRAY?

[英]How do you access to SAFE ARRAY in a VARIANT data type returned from a COM object in C++?

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

  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);
                    }
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM