How do I copy a BSTR to an IStream

  • Thread starter Thread starter Charles Law
  • Start date Start date
C

Charles Law

Could anyone please tell me what is wrong with the code below:

STDMETHODIMP CSimpleObj::WriteUnmanagedData(BSTR pString, IStream** ppData)
{
HRESULT hr;

hr = CreateStreamOnHGlobal(0, TRUE, ppData);

if (FAILED(hr))
return hr;

ULONG lBytesWritten;

hr = (*ppData)->Write(pString, SysStringLen(pString), &lBytesWritten);
//hr = (*ppData)->Write("This is unmanaged data.", 24, &lBytesWritten);

if (FAILED(hr))
return hr;

return S_OK;
}

The line commented out works as expected (copies the whole string). The line
above it only seems to copy one character (the first character). No doubt I
have made a trivial mistake, but please humour me.

Thanks for any help.

Charles
 
I am sure this one isn't a tricky problem, it's just that I don't know how
to do it, and it's really holding me up.

Could someone please help?

TIA

Charles
 
Hi Charles,

Usually when someone has a problem like this it is a UNICODE issue. Your
BSTR will be a UNICODE string so you are only writing half of it into ppData
to start with. How do know you only get one character? If you subsequently
assume the stream contains an ordinary string then the second byte of the
first UNICODE char will likely be null marking the end of an ordinary
string.

Cheers

Doug Forster
 
Hi Doug

I am actually calling the WriteUnmanagedData() function from VB.NET (I want
to get a string into an IStream so that I can use the WebBrowser control to
load HTML from a stream).

The code for the call is:

Dim Strm As UnmanagedFuncs.IStream
Dim myComObject As CSimpleObjClass
Dim encoding As System.Text.Encoding = System.Text.Encoding.ASCII

'Get an instance of your unmanaged COM object and get some stream data
from it.
myComObject = New CSimpleObjClass
myComObject.WriteUnmanagedData("This is unmanaged data", Strm)

'Create an instance of an object of your ComStream class.
Dim StreamObj As ComStream

StreamObj = New ComStream(Strm)

'Display the contents of the stream using the StreamReader class.
Dim sr As StreamReader

sr = New StreamReader(StreamObj)
StreamObj.Seek(0, SeekOrigin.Begin)

Debug.WriteLine("---STREAM CONTENTS---")
Debug.WriteLine(sr.ReadToEnd())

When the literal text is written into the BSTR it is displayed in full
within the VB app, but when the passed string is written only the 'T' is
displayed.

You could be right about the Unicode thing, but I don't know how I can tell
from he code I have included, or is there more to it?

Cheers

Charles
 
Back
Top