Thanks for the tip. This is what I ended up with:
.CPP file ------------------------
#include <iostream> #include <sstream> static std::stringstream buffer; static std::streambuf * savedBuffer = NULL; extern "C" __declspec(dllexport) bool Redirect() { if (savedBuffer) { return false; } std::streambuf * buf(std::cerr.rdbuf()); std::cerr.rdbuf(buffer.rdbuf()); // This two lines are for illustration purposes only! std::cerr << "Hello world" << std::endl; return true; } extern "C" __declspec(dllexport) void Revert() { if (savedBuffer) { std::cerr.rdbuf(savedBuffer); } savedBuffer = NULL; } extern "C" __declspec(dllexport) const char * getCerr() { return _strdup(buffer.str().c_str()); } extern "C" __declspec(dllexport) void freeCharPtr(char *ptr) { free(ptr); }
.CS file ------------------------------------------
public static class Redirector {
NUnit Test -----------------------
[Test]
The freeCharPtr () file is needed to free allocated memory from _strdup (), since I could not work (if it was possible) how to marshal std :: string.
Note. It is not safe for threads!
source share