2013-11-14 74 views

回答

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); 
} 
+0

WOW是真正的最簡單的方法Concat的2串。我習慣了C#,它只是aString + bString;沒有現有的方法可以做到這一點?哇!!! C++很爛 – user565660

+3

@ user565660'BSTR'很糟糕。 'BSTR'是一個基於C的接口。給你帶有價值的字符串的包裝器存在,但不是'BSTR'。 – Yakk

+0

@ user565660:再說一遍「C++吸吮」,它就會在腳下射擊你。 Yeap,用*低俗小說*電影的方式。 – sharptooth

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; 
+0

pOne和pTwo不是BSTR。你必須使用SysAllocX函數來獲得真正的BSTR(它們有一個4字節的長度「前綴」,排序) – manuell

+0

@manuell我站在更正!非常感謝,我修改了我的答案。以前的版本確實編譯好,但不起作用,就像[這裏說的](http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v = vs.85).aspx )。 –

相關問題