C++: Convert wchar_t* to BSTR?
Asked Answered
Y

3

6

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

#include <iostream>
#include <atlstr.h>

using namespace std;

int main()
{
    wchar_t* pwsz = L"foo"; 

    BSTR bstr(pwsz);

    cout << SysStringLen(bstr) << endl;

    getchar();
}

This prints 0, which is less than what I'd hoped. What is the correct way to do this conversion?

Yseulte answered 23/7, 2010 at 23:53 Comment(0)
J
11

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.

Jalbert answered 23/7, 2010 at 23:56 Comment(0)
O
2

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.

Optometry answered 26/7, 2010 at 5:13 Comment(0)
C
1

I think easiest is either to use

CString

or

CComBSTR

both have methods that do what Charles mentioned

Clisthenes answered 24/7, 2010 at 0:35 Comment(2)
CString doesn't wrap a BSTR, although it has a method to allocate a BSTR from a CString ( .AllocSysString() ). CString doesn't help with automatic freeing of a BSTR, though.Jalbert
well in a sense it wraps the functionality to convert to a BSTR which was what the OP wanted, but technically you are correct so my choice of words was not right.Clisthenes

© 2022 - 2024 — McMap. All rights reserved.