Is it possible to wrap a .net stream as stl std :: ostream *?

I have an unmanaged C ++ library that outputs text to std :: ostream *.

I call this from a managed C ++ shell, which is used by the C # library.

I am currently passing unmanaged code to a pointer to std :: stringstream, and then System.String (stringstream.str (). C_str ()) is called later to copy my unmanaged buffer back to a .net-friendly string.

Is it possible to wrap a .net stream as stl std :: ostream *? - allows me to transfer text directly from my unmanaged code to a managed implementation of STREAM.

+4
source share
2 answers

If I understand correctly, you want to wrap a .NET stream with a std C ++ stream so that your own code is passed to the std C ++ stream, but the data goes into the .NET stream.

C ++ IO streams are roughly divided into the streams themselves, which perform all the conversions between the C ++ types and the binary representation, and the stream buffers that buffer data and read from / write to the device. What you need to do to achieve your goal is to use a stream buffer that writes to the .NET stream. To do this, you need to create your own stream buffer, obtained from std::stream_buffer , which internally refers to the .NET stream and sends all the data to it. This is what you pass to the std::ostream , which is passed into native code.

Writing your own stream buffer is not a novice task, but it is not particularly difficult. Choose any worthy link to IO C ++ streams ( Langer / Kreft is the best you can get on paper), find out which of the virtual functions you need to rewrite to do this, and you're done.

+6
source

Can you do this. Just create your own class that comes from Stream and implements the appropriate methods.

In this case, you need to set CanRead to true and implement at least Read or ReadByte . When you create them, just read from the output stream on the home side.

This will allow you to "transfer" data from your own stream to the .NET stream and will work with any of the stream reading classes in .NET.

+2
source

All Articles