使用_bstr_t在函数中传递BSTR*类型的参数

Asi*_*sim 9 c++ bstr

这样做的正确方法是什么:

_bstr_t description;
errorInfo->GetDescription( &description.GetBSTR() );
Run Code Online (Sandbox Code Playgroud)

要么:

_bstr_t description;
errorInfo->GetDescription( description.GetAddress() );
Run Code Online (Sandbox Code Playgroud)

在哪里IError:GetDescription定义为:

HRESULT GetDescription (BSTR *pbstrDescription);
Run Code Online (Sandbox Code Playgroud)

我知道我可以轻松地做到这一点:

BSTR description= SysAllocString (L"Whateva"));
errorInfo->GetDescription (&description);
SysFreeString (description);
Run Code Online (Sandbox Code Playgroud)

谢谢

Han*_*ant 9

BSTR是引用计数,我严重怀疑如果你使用GetAddress()将会正常工作.可悲的是,源代码无法进行仔细检查.我总是这样做:

BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
    _bstr_t wrap(temp, FALSE);
    // etc..
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*end 5

要跟进@Hans的回答 - 构建它的适当方法_bstr_t取决于GetDescriptionBSTR是否拥有自己拥有的,或者引用你不需要释放的记忆.

这里的目标是最小化副本数量,但也避免SysFreeString对返回的数据进行任何手动调用.我会修改代码,如图所示澄清:

BSTR temp = 0;
HRESULT hr = p->GetDescription(&temp);
if (SUCCEEDED(hr)) {
    _bstr_t wrap(temp, false);    // do not copy returned BSTR, which
                                  // will be freed when wrap goes out of scope.
                                  // Use true if you want a copy.
    // etc..
}
Run Code Online (Sandbox Code Playgroud)