Redirecting native dll stdout/stderr from within C#

旧城冷巷雨未停 提交于 2019-12-05 02:20:34

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/1430213/redirecting-native-dll-stdout-stderr-from-within-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!