Redirecting std::cout in managed apps
I recently needed to write a library in Managed C++ that wrapped another native C++ library. I wanted to display the output from the native lib in a C# application. With a little help from Google I ended up with this.
/redirector.h
It is simply an implementation of a streambuf, that has a System::String object as an internal buffer and a System.IO.TextWriter to redirect the output to. Thanks to the gcroot functionality that allows us to have a managed reference in an unmanaged class.
The following code installs the redirector:
With writer a managed reference to the TextWriter of your choice. Keep a pointer to the standard streambuf to put it back if needed.
This captures all output to std::cout (and possible std::cerr). But for capturing output with printf we need another trick. I didn't need that yet so I didn't delve into that, but maybe later I will, and then I'll post an update.
Feel free to comment.
/redirector.h
It is simply an implementation of a streambuf, that has a System::String object as an internal buffer and a System.IO.TextWriter to redirect the output to. Thanks to the gcroot functionality that allows us to have a managed reference in an unmanaged class.
The following code installs the redirector:
COutputRedirector *redirectedOut = new COutputRedirector(writer);
std::streambuf* stdCout = std::cout.rdbuf(redirectedOut);
With writer a managed reference to the TextWriter of your choice. Keep a pointer to the standard streambuf to put it back if needed.
This captures all output to std::cout (and possible std::cerr). But for capturing output with printf we need another trick. I didn't need that yet so I didn't delve into that, but maybe later I will, and then I'll post an update.
Feel free to comment.


0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home