How to pass SAFEARRAY to COM object through IDispatch?

耗尽温柔 提交于 2019-11-29 04:33:22

This should give you some insight:

On the caller side, C# code:

Foo foo = new Foo();
byte[] input = new byte[] { 1, 2, 3, 4 };
byte[] output = foo.Bar(input);
byte[] referenceOutput = new byte[] { 4, 3, 2, 1 };
Debug.Assert(Enumerable.SequenceEqual(output, referenceOutput));

The Foo.Bar IDL:

interface IFoo : IDispatch
{
    [id(1)] HRESULT Bar([in] VARIANT vInput, [out, retval] VARIANT* pvOutput);
};

And C++ (ATL) server implementation with safe arrays:

// IFoo
    STDMETHOD(Bar)(VARIANT vInput, VARIANT* pvOutput) throw()
    {
        _ATLTRY
        {
            ATLENSURE_THROW(vInput.vt == (VT_ARRAY | VT_UI1), E_INVALIDARG);
            CComSafeArray<BYTE> pInputArray(vInput.parray);
            ATLASSERT(pInputArray.GetDimensions() == 1);
            const ULONG nCount = pInputArray.GetCount();
            CComSafeArray<BYTE> pOutputArray;
            ATLENSURE_SUCCEEDED(pOutputArray.Create(nCount));
            for(ULONG nIndex = 0; nIndex < nCount; nIndex++)
                pOutputArray[(INT) nIndex] = pInputArray[(INT) ((nCount - 1) - nIndex)];
            ATLASSERT(pvOutput);
            VariantInit(pvOutput);
            CComVariant vOutput(pOutputArray.Detach());
            ATLVERIFY(SUCCEEDED(vOutput.Detach(pvOutput)));
        }
        _ATLCATCH(Exception)
        {
            return Exception;
        }
        return S_OK;
    }

Source: Trac, Subversion - beware Visual Studio 2012.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!