Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

.net

stream

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.

like image 835
morechilli Avatar asked Mar 01 '23 06:03

morechilli


1 Answers

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.

like image 124
sbi Avatar answered Mar 02 '23 18:03

sbi