简体   繁体   English

从C#中重定向本机dll stdout / stderr

[英]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#. 我正在尝试重定向从C#中输出到stdout / stderr的第三方本机dll的输出。 The output of both stdout and stderr should go to a log file. stdout和stderr的输出应该转到日志文件。

Here's my idea (x2 for two streams): 这是我的想法(两个流的x2):

  • Create an AnonymousPipeServerStream 创建AnonymousPipeServerStream
  • Get the pipe's handle via _outServer.SafePipeHandle.DangerousGetHandle() 通过_outServer.SafePipeHandle.DangerousGetHandle()获取管道的句柄
  • Use P/Invoke to call SetStdHandle with said handle 使用P / Invoke用所述句柄调用SetStdHandle
  • Create an AnonymousPipeClientStream connected to the server stream 创建连接到服务器流的AnonymousPipeClientStream
  • Create a thread to sit in a loop reading from the AnonymousPipeClientStream and outputting to the logger. 创建一个线程,以便从AnonymousPipeClientStream读取循环并输出到记录器。
  • Periodically call flush on the AnonymousPipeServerStream 定期在AnonymousPipeServerStream上调用flush

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! 一旦控件传递给本机DLL,一切都会回到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? 如果需要,我可以调试到本机DLL,看看出了什么问题,但是......我真的不愿意,所以在我花了10个小时试图找出句柄如何工作之前,有没有人有任何想法?

For reference, the test code is at: http://pastebin.com/f3eda7c8 . 作为参考,测试代码位于: http//pastebin.com/f3eda7c8 The interesting stuff is lines 58-89 in the constructor. 有趣的东西是构造函数中的第58-89行。 (I'll add error handling, etc. later, of course). (当然,我稍后会添加错误处理等)。

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. dll是用mingw编译的,显然不尊重MSVC运行时使用的句柄。

I'll leave the code & solution up in case anyone else encounters this problem. 我将保留代码和解决方案,以防其他人遇到此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM