Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting native dll stdout/stderr from within C#

I'm trying to redirect the output of a third-party native dll which outputs to stdout/stderr from within C#. The output of both stdout and stderr should go to a log file.

Here's my idea (x2 for two streams):

  • Create an AnonymousPipeServerStream
  • Get the pipe's handle via _outServer.SafePipeHandle.DangerousGetHandle()
  • Use P/Invoke to call SetStdHandle with said handle
  • Create an AnonymousPipeClientStream connected to the server stream
  • Create a thread to sit in a loop reading from the AnonymousPipeClientStream and outputting to the logger.
  • Periodically call flush on the AnonymousPipeServerStream

So all this seems to be working well... within my code. As soon as control passes to the native DLL, everything goes back to stderr! If need be, I can debug into the native DLL and see what's going wrong, but... I'd really rather not, so does anyone have any ideas before I spend 10 hours trying to figure out how handles work?

For reference, the test code is at: http://pastebin.com/f3eda7c8. The interesting stuff is lines 58-89 in the constructor. (I'll add error handling, etc. later, of course).

like image 605
Robert Fraser Avatar asked Sep 15 '09 23:09

Robert Fraser


1 Answers

I solved it, though the solution (of course) has very little to do with the problem. The dll was compiled in mingw, which apparently doesn't respect the handles used by the MSVC runtime.

I'll leave the code & solution up in case anyone else encounters this problem.

like image 91
Robert Fraser Avatar answered Nov 04 '22 07:11

Robert Fraser