2012-02-04 44 views
2

我想獲取重定向到C#控制檯的C++控制檯輸出(printf(「」)語句)。將C++控制檯輸出重定向到C#控制檯不會打印任何東西

以下是我所得到

 Process e = new Process(); 
     e.StartInfo.UseShellExecute = false; 
     e.StartInfo.RedirectStandardOutput = true; 
     e.StartInfo.FileName = "C:\\Users\\Projects\\ot\\x64\\Debug\\ot.exe"; 
     e.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); 
     e.Start(); 
     e.BeginOutputReadLine(); 

但我沒有得到任何輸出。 C++控制檯不會打印任何東西(這意味着輸出已被重定向),這些代碼行都不是C#。

我該如何解決這個問題?

感謝,

+0

[OutputDataReceived](http://msdn.microsoft.com/zh-cn/library/system.diagnostics.process.outputdatareceived.aspx)上有一個很大的黃色註釋,​​它表示「正在處理異步輸出應調用WaitForExit()方法以確保輸出緩衝區已被刷新。「 – 2012-02-04 14:29:11

+0

謝謝你的回覆雷蒙德。但WaitForExit()也是如此。其實我的C++是一個使用OpenCV的應用程序。 當我使用OpenCV相關函數時,只有printf語句不會重定向到C#控制檯。就像我使用, CvCapture * capture = cvCaptureFromCAM(1); 後printf語句不會重定向到C#控制檯。 – Gimz 2012-02-06 04:02:23

回答

0

嘗試使用:

Process e = new Process(); 
    e.StartInfo.UseShellExecute = false; 
    e.StartInfo.RedirectStandardOutput = true; 
    e.StartInfo.RedirectStandardError = true; 
    e.StartInfo.FileName = "C:\\Users\\Projects\\ot\\x64\\Debug\\ot.exe"; 
    e.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); 
    e.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data); 
    e.Start(); 
    e.BeginOutputReadLine(); 
    e.BeginErrorReadLine(); 
    e.WaitForExit(); 
    e.CancelErrorRead(); 
    e.CancelOutputRead(); 

我已經把可以用來包裹process class和幫助與其他進程交互的基類。

+0

歡迎來到堆棧溢出。請注意答案應該是獨立的;儘管鏈接可能用於提供資源和附加信息,但實際的解決方案應該包含在答案中。請訪問[幫助中心](http://stackoverflow.com/help/how-to-answer)以獲取有關回答本網站上問題的指導。 – McMath 2016-02-27 10:33:36