C++: Convert wchar_t* to BSTR?

前端 未结 3 827
执念已碎
执念已碎 2021-01-13 05:42

I\'m trying to convert a wchar_t * to BSTR.

#include 
#include 

using namespace std;

int main()
         


        
相关标签:
3条回答
  • 2021-01-13 06:24

    You need to use SysAllocString (and then SysFreeString).

    BSTR bstr = SysAllocString(pwsz);
    
    // ...
    
    SysFreeString(bstr);
    

    A BSTR is a managed string with the characters of the string prefixed by their length. SysAllocString allocates the correct amount of storage and set up the length and contents of the string correctly. With the BSTR correctly initialized, SysStringLen should return the correct length.

    If you're using C++ you might want to consider using a RAII style class (or even Microsoft's _bstr_t) to ensure that you don't forget any SysFreeString calls.

    0 讨论(0)
  • 2021-01-13 06:34

    SysStringLen() should only be used on BSTRs allocated by SysAllocString() family functions. Using it as you do will lead to undefined behavior - program can crash or produce unexpected results. Better yet use wrapper classes - ATL::CComBSTR or _bstr_t.

    0 讨论(0)
  • 2021-01-13 06:41

    I think easiest is either to use

    CString

    or

    CComBSTR

    both have methods that do what Charles mentioned

    0 讨论(0)
提交回复
热议问题