user565660
user565660

Reputation: 1191

What is the best way to concatenate two BSTRs?

I have tried a few different way to concatenate two BSTRs and haven't haven't found a gopd way of doing. I haven't found anything on the web at all.

Upvotes: 2

Views: 6808

Answers (2)

Roger Rowland
Roger Rowland

Reputation: 26259

You can use the _bstr_t wrapper:

#include <comutil.h>

#pragma comment(lib, "comsupp.lib")

// you have two BSTR's ...
BSTR pOne = SysAllocString(L"This is a ");
BSTR pTwo = SysAllocString(L"long string");

// you can wrap with _bstr_t
_bstr_t pWrapOne = pOne;
_bstr_t pWrapTwo = pTwo;

// then just concatenate like this
_bstr_t pConcat =  pWrapOne + pWrapTwo;

Upvotes: 2

hansmaad
hansmaad

Reputation: 18905

You should use a wrapper like ATL CComBSTR that also handles resource management for you.

Without a wrapper you have do:

BSTR Concat(BSTR a, BSTR b)
{
    auto lengthA = SysStringLen(a);
    auto lengthB = SysStringLen(b);

    auto result = SysAllocStringLen(NULL, lengthA + lengthB);

    memcpy(result, a, lengthA * sizeof(OLECHAR));
    memcpy(result + lengthA, b, lengthB * sizeof(OLECHAR));

    result[lengthA + lengthB] = 0;
    return result;
}

int main()
{
    auto a = SysAllocString(L"AAA");
    auto b = SysAllocString(L"BBB");
    auto c = Concat(a, b);
    std::wcout << a << " + " << b << " = " << c << "\n";

    SysFreeString(a);
    SysFreeString(b);
    SysFreeString(c);
}

Upvotes: 2

Related Questions