【问题标题】:Redirection of C++ console output to C# console doesn't print anything将 C++ 控制台输出重定向到 C# 控制台不打印任何内容
【发布时间】:2012-02-04 13:40:17
【问题描述】:

我想将 C++ 控制台的输出(printf("") 语句)重定向到 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#。

我该如何解决这个问题?

谢谢,

【问题讨论】:

  • OutputDataReceived 上有一个大大的黄色注释,​​上面写着“正在处理异步输出的应用程序应该调用 WaitForExit() 方法以确保输出缓冲区已被刷新。”
  • 感谢雷蒙德的回复。但 WaitForExit() 也一样。实际上我的 C++ 是一个使用 OpenCV 的应用程序。当我使用 OpenCV 相关函数时,只有 printf 语句不会重定向到 C# 控制台。如果我使用,CvCapture* capture = cvCaptureFromCAM(1);在不会重定向到 C# 控制台的 printf 语句之后。

标签: c# c++ redirect


【解决方案1】:

尝试使用:

    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 并帮助与其他进程交互。

【讨论】:

  • 欢迎来到 Stack Overflow。请注意,答案应该是独立的;虽然链接可用于提供资源和附加信息,但实际解决方案应包含在答案本身中。请访问help center 获取有关在本网站上回答问题的指导。
猜你喜欢
  • 1970-01-01
  • 2011-03-08
  • 2021-06-20
  • 1970-01-01
  • 2021-06-05
  • 2015-09-11
  • 2011-05-28
  • 2013-11-14
  • 1970-01-01
相关资源
最近更新 更多