How does one return a local CComSafeArray to a LPSAFEARRAY output parameter?

后端 未结 3 2213
花落未央
花落未央 2021-02-20 05:35

I have a COM function that should return a SafeArray via a LPSAFEARRAY* out parameter. The function creates the SafeArray using ATL\'s CComSafeArray te

相关标签:
3条回答
  • 2021-02-20 05:53

    The problem is that you set the receiving CComSafeArray's internal pointer directly. Use the Attach() method to attach an existing SAFEARRAY to a CComSafeArray:

    LPSAFEARRAY ar;
    foo(&ar);
    CComSafeArray<VARIANT> sa;
    sa.Attach(ar);
    
    0 讨论(0)
  • 2021-02-20 05:57

    Just to confirm that the marked answer is the correct one. RAII wrappers cannot work across COM boundaries.

    The posted method implementation is not correct, you cannot assume that the caller is going to supply a valid SAFEARRAY. Just [out] is not a valid attribute in Automation, it must be either [out,retval] or [in,out]. If it is [out,retval], which is what it looks like, then the method must create a new array from scratch. If it is [in,out] then the method must destroy the passed-in array if it doesn't match the expected array type and create a new one.

    0 讨论(0)
  • 2021-02-20 06:05

    I'd guess that where was no intent to allow such a use case. Probably it was not the same developer who wrote CComVariant & CComPtr :)

    I believe that CComSafeArray's author considered value semantics as major goal; Attach/Detach might simply be a "bonus" feature.

    0 讨论(0)
提交回复
热议问题