tags:

views:

118

answers:

2

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

I call this from a managed c++ wrapper that is used by a c# library.

Currently I pass the unmanaged code a pointer to a std::stringstream and then later call System.String(stringstream.str().c_str()) to copy my unmanaged buffer back into a .net friendly string.

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

+1  A: 

You can do this. Just create a custom class that derives from Stream, and implements the appropriate methods.

In this case, you'll want to set CanRead to true, and implement, at a minimum, Read or ReadByte. When you impelment them, just read from the output stream on the native side.

This will allow you to "stream" data from your native ostream to a .NET stream, and will work with any of the stream reader classes in .NET.

Reed Copsey
I think he needs it the other way around - so it would be a custom class deriving from `std::ostream` and wrapping `System.IO.Stream`.
Pavel Minaev
Not 100% sure, when I read it. EIther way, it's fairly easy to pass data from a .NET stream into a native stream, in either direction.
Reed Copsey
+3  A: 

If I understood correctly, you want to wrap a .NET stream with a C++ std stream, so that your native code streams into the C++ std stream, but the data ends up in the .NET stream.

C++ IO streams roughly split into the streams themselves, which do all of the conversion between the C++ types and a binary representation, and the stream buffers, which buffer the data and read from/write to a device. What you would need to do in order to achieve you goal is to use a stream buffer that writes to a .NET stream. In order to do this, you need to create your own stream buffer, derived from std::stream_buffer, which internally references a .NET stream and forwards all data to it. This you pass to the std::ostream object which is passed to the native code.

Writing your own stream buffer isn't a beginner's task, but it isn't particularly hard either. Pick any decent reference on C++ IO streams (Langer/Kreft is the best you can get on paper), find out which of the virtual functions you need to overwrite in order to do that, and you're done.

sbi
Thanks - that makes sense - I'd missed the stream buffer split.
morechilli