我尝试了几种不同的方法来连接两个 BSTR,但还没有找到 gopd 的做法。我在网上根本没有找到任何东西。
问问题
5780 次
2 回答
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;
于 2013-11-14T13:11:00.640 回答
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);
}
于 2013-11-14T12:41:55.547 回答