6

I have a C# Console app that P/Invokes into a native C++ dll. The dll creates some threads which are very chatty and write their logs into standard outputs. The problem is that I need Console for my user interactions.

How can I redirect the dll stdout/stderr to null?

MBZ
  • 26,084
  • 47
  • 114
  • 191
  • Could you change your code so that it makes the calls to the C++ DLL in a separate process? If so you could launch the separate process with the `ProcessWindowStyle.Hidden` option. It may not be exactly what your are looking for, but it would work. – shf301 Apr 27 '14 at 19:25

2 Answers2

2

I think than, in order to make this work you will need to build a native DLL that links to the same C++ runtime as the troublesome DLL. You'll then need to use freopen to redirect the stdout. My source for this code is this answer: freopen: reverting back to original stream

The C++ code would look like this:

#include <io.h>

__declspec(dllexport) void RedirectStdOutputToNul(int *fd, fpos_t *pos)
{
    fflush(stdout);
    fgetpos(stdout, pos);
    *fd = _dup(fileno(stdout));
    freopen("NUL", "w", stdout);
}

__declspec(dllexport) void RestoreStdOutput(int fd, fpos_t pos)
{
    fflush(stdout);
    _dup2(fd, fileno(stdout));
    close(fd);
    clearerr(stdout);
    fsetpos(stdout, &pos);      
}

You can p/invoke that from your code like this:

[DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
static extern void RedirectStdOutputToNul(out int fd, out long pos);

[DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
static extern void RestoreStdOutput(int fd, long pos);

And you might call it like this:

int fd;
long pos;

RedirectStdOutputToNul(out fd, out pos);
print("boo");
RestoreStdOutput(fd, pos);
print("yah");

All this relies upon the DLL linking to a dynamic MSVC runtime and you being able to write code that links to same.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
-2

I'm a little confused by your question, does the C# app invoke the C++, or the other way around?

Either way, my response is the same for both. Pipe the output of the offending thread into /dev/null (a log would be preferable though...)

If you have control over the c++ dll, use: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx

Else: Redirecting standard input of console application

Pipe's are awesome. I regularly pipe output into null when I don't want to see the output on the terminal, and I don't feel like remembering how to cause a silent run.

Community
  • 1
  • 1
Samuel Fleming
  • 147
  • 1
  • 6