如何将值从safearray复制到vector?

时间:2014-03-03 13:04:03

标签: c++ vector stl safearray

我有一个电话返回BSTR的safearray。我想将其复制到vector<LPOLESTR>。这样做的正确方法是什么?在这种情况下如何处理内存?

1 个答案:

答案 0 :(得分:2)

假设你想要vector<wstring>,请在评论中进行讨论,如下所示:

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

错误处理留给读者练习。