Search code examples
c++vectorstlsafearray

How to copy values from safearray to vector?


I have a call returning safearray of BSTR. I want to copy it to a vector<LPOLESTR>. What is the correct way to do it? How is the memory handled in this case?


Solution

  • Assuming you want vector<wstring> after all, per discussion in comments, something like this:

    SAFEARRAY* sa;  // a safearray of BSTR, initialized somehow.
    
    LONG lBound, uBound;
    SafeArrayGetLBound(sa, 1, &lBound);
    SafeArrayGetUBound(sa, 1, &uBound);
    LONG count = uBound - lBound + 1;  // bounds are inclusive
    
    BSTR* raw;
    SafeArrayAccessData(sa, (void**)&raw);
    
    vector<wstring> v(raw, raw + count);
    // or, if you want to assign to an existing vector
    vector<wstring> v;
    v.assign(raw, raw + count);
    
    // When no longer need "raw".
    SafeArrayUnaccessData(sa);
    

    Error handling is left as an exercise for the reader.