Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Convert wchar_t* to BSTR?

Tags:

c++

string

com

bstr

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?

like image 791
Nick Heiner Avatar asked Jul 23 '10 23:07

Nick Heiner


1 Answers

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.

like image 84
CB Bailey Avatar answered Oct 30 '22 00:10

CB Bailey