是否从记录集中返回BSTR

问题描述 投票:0回答:1

这里有一些ADODB代码从记录集中检索BSTR,但我不确定是否应该使用SysFreeString释放BSTR。现在它是,它似乎工作,但你应该自己做吗?

    BSTR bstr = m_pRecordset->Fields->GetItem ( field )->Value.bstrVal;

    int len = SysStringLen(bstr);

    while (len > 0 && iswspace(bstr[len-1])) len--;

    BSTR newstr = SysAllocStringLen(bstr, len);

    SysFreeString(bstr);
    SysFreeString(newstr);
mfc com ado
1个回答
2
投票

你的代码错了。 m_pRecordset->Fields->GetItem ( field )->Value返回VARIANT作为_variant_t

您应该将对象保存在临时变量中,访问数据,析构函数将完成剩下的工作。

_variant_t val = m_pRecordset->Fields->GetItem ( field )->Value;

int len = SysStringLen(val.bstrVal);

while (len > 0 && iswspace(bstr[len-1])) len--;

BSTR newstr = SysAllocStringLen(val.bstrVal, len);
...
SysFreeString(newstr);

See sample here in the MSDN.

还应该提到的是,最好使用CComBSTR_bstr_t而不是BSTR。

© www.soinside.com 2019 - 2024. All rights reserved.