views:

50

answers:

1

I am working on a web browser with c++ using IWebBrowser2. Declared on the top, outside any scope, I have this:

static char buf[1024];

In the documentcomplete event, I set the BSTR with:

CComBSTR bstrHTMLText;
X->get_outerHTML(&bstrHTMLText);

What I want to do is to copy bstrHTMLText value into buf (if bstrHTMLText length is > 1024 just fill buf and ignore the rest). every time documentcomplete fires.

How can I do this?

+1  A: 

A BSTR is secretly a pointer to a Unicode string, with a hidden length prefix sitting in front of the string data. So, you can just cast it to wchar_t* and then convert that wide-character string to an ANSI string, e.g. using WideCharToMultiByte:

WideCharToMultiByte(CP_UTF8,
                    0, 
                    bstrHTMLText.m_str,
                    SysStringLen(bstrHTMLText.m_str),
                    buf,
                    sizeof(buf),
                    NULL,
                    NULL);
Adam Rosenfield
Careful with this. It will normally (perhaps always) work, but there are two potential gotchas: NULL is a valid BSTR, and BSTR's are not necessarily NULL-terminated (per the spec). Your solution will probably usually work in practice (and I've seen plenty of code do the equivalent), but it's not technically correct.
Nick
What would be technically correct to achieve this?
gtilx