You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinRT中是否有拼接两个wil::unique_bstr字符串的方法?

关于WIL库中wil::unique_bstr的字符串拼接方法

问题描述

我正在将遗留代码移植到WinRT组件,已经用wil::unique_bstr替换了CComBSTR。原代码里可以通过a += b实现字符串拼接,现在想知道WIL库有没有直接拼接两个wil::unique_bstr的方法。我试过把BSTR转成std::wstring用STL操作,但要改的地方太多,希望直接用BSTR完成拼接。

解决方案

WIL库本身没有为wil::unique_bstr提供直接的operator+=重载,但可以通过以下两种方式实现拼接:

方法一:手动封装拼接函数

借助系统APISysAllocStringLen和SysStringLen手动分配新BSTR并复制内容,封装成复用函数:

wil::unique_bstr concat_unique_bstr(const wil::unique_bstr& str1, const wil::unique_bstr& str2)
{
    if (!str1) return wil::unique_bstr(str2.get());
    if (!str2) return wil::unique_bstr(str1.get());

    const UINT len1 = SysStringLen(str1.get());
    const UINT len2 = SysStringLen(str2.get());
    wil::unique_bstr result(SysAllocStringLen(nullptr, len1 + len2));
    if (!result) return {};

    wcscpy_s(result.get(), len1 + len2 + 1, str1.get());
    wcscat_s(result.get(), len1 + len2 + 1, str2.get());
    return result;
}

使用示例:

wil::unique_bstr a(L"First part");
wil::unique_bstr b(L"Second part");
auto combined = concat_unique_bstr(a, b);

方法二:自定义operator+=重载

如果想保留原代码a += b的写法,可以自行添加operator+=重载:

wil::unique_bstr& operator+=(wil::unique_bstr& lhs, const wil::unique_bstr& rhs)
{
    if (!rhs) return lhs;
    if (!lhs) {
        lhs = wil::unique_bstr(rhs.get());
        return lhs;
    }

    const UINT lenLhs = SysStringLen(lhs.get());
    const UINT lenRhs = SysStringLen(rhs.get());
    wil::unique_bstr temp(SysAllocStringLen(nullptr, lenLhs + lenRhs));
    if (!temp) {
        lhs.reset(); // 分配失败时清空,避免内存泄漏
        return lhs;
    }

    wcscpy_s(temp.get(), lenLhs + lenRhs + 1, lhs.get());
    wcscat_s(temp.get(), lenLhs + lenRhs + 1, rhs.get());
    lhs.swap(temp);
    return lhs;
}

使用示例:

wil::unique_bstr a(L"Hello");
wil::unique_bstr b(L" World");
a += b;

注意:自定义重载时要确保作用域正确,避免与其他代码定义冲突。

内容的提问来源于stack exchange,提问作者Snekithan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:16:02