how do I get an byte[] from HGLOBAL?

Jul 22, 2010 at 5:59am
Hi there,

I am writing some XML to a stream using XMLLite. xmlOut is a byte array class that I use.

When I'm done writing the XML I want to get the stream back into my byte array to encrypt.

Could anybody give me some pointers on how to get the stream to byte[]?

Here is some of my code.

CComPtr<IStream> outStream;

HGLOBAL hOutBuffer = ::GlobalAlloc(GMEM_MOVEABLE, xmlOut.GetLen() );
void* pOutBuffer = ::GlobalLock(hOutBuffer);
CopyMemory( pOutBuffer, xmlOut.GetData(), xmlOut.GetLen() );
CHECKHR(::CreateStreamOnHGlobal( hOutBuffer, FALSE, &outStream ));
CHECKHR( pWriter->SetOutput(outStream) );

//reading and writing XML here

//copy hOutbuffer back into xmlOut here??

I'm new to c++ so please excuse me if I missed something obvious.

thank you,
Jul 22, 2010 at 8:34am
You mean you still have hOutBuffer but don't have pOutBuffer anymore?

BTW, why are you using GlobalAlloc/GlobalLock?
Jul 22, 2010 at 9:55am
:-)

I'm not sure why. The other person that worked on the project used it when he read the xml. He's very clever so I thought it would be the right thing to do :-)

I have a xmlfile in a byte array that I copy to pInBuffer using GlobalAllco/GlobalLock. Then I read throught the xml, make some changes and want to get it back into a byte array to use elsewhere.

Like I said I'm new :-) I still have pOutBuffer. Tried to do (byte*) pOutBuffer -> no luck.
Jul 22, 2010 at 3:25pm
You have to write your XML with an IXmlWriter. The IXmlReader only parses, while and IXmlWriter only writes.

This has an example how to use the two in conjunction to read-modify-write some XML.
http://blogs.msdn.com/b/mfussell/archive/2005/02/12/371546.aspx

Your example confusingly declares an IXmlReader as outStream, you really should call it inStream.

The code you've posted is intermediate code to get your XML from a plain old memory buffer (I hope it's Unicode and not chars) into an IXmlReader, but using memory stream.

how do I get an byte[] from HGLOBAL?
I hope you now realise this is an irrelvant question. You only used GlobalAlloc because that's what CreateStreamOnHGlobal required. And you used CreateStreamOnHGlobal because the IXmlReader is initialised from an IStream. Once that's done, it's done.

To reiterate, you need to populate an IXmlWriter and use that to write into another IStream.

XMLLite may be lite by Microsoft Standards, but it seems to be hampered by that COM interface and someone's idea of a clever abstraction. There's a lot to be said for something really simple like TinyXML.
Last edited on Jul 22, 2010 at 4:04pm
Topic archived. No new replies allowed.