我尝试了几种不同的方法来连接两个BSTR,并且还没有找到一种gopd方法。我根本没有在网上找到任何东西。
答案 0 :(得分:2)
您应该使用像ATL CComBSTR这样的包装器来处理资源管理。
如果没有包装器,你可以这样做:
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);
}
答案 1 :(得分:2)
您可以使用_bstr_t
包装器:
#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;