将printf C ++控制台输出重定向到C#

时间:2012-06-14 08:18:38

标签: c# c++ redirect

这是我单击C#GUI程序中的按钮时调用的方法。它启动了一个非常简单的C ++控制台程序,除了在永无止境的循环中每秒打印一行外,什么都不做。

private static Process process;

private void LaunchCommandLineApp()
{
    process = new Process();
    process.StartInfo.FileName = "SimpleTest.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.EnableRaisingEvents = true;
    process.StartInfo.CreateNoWindow = false;
    process.OutputDataReceived += process_OutputDataReceived;

    process.Start();
    process.BeginOutputReadLine();
}

这是处理收到的任何输出数据的方法:

private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
        Console.WriteLine(e.Data.ToString());
}

我的C#调试输出中没有看到任何输出... 但是,如果我将printf更改为std :: cout,它将显示重定向的消息。

我在想是否有办法用printf显示这些陈述?

仅供参考:我的c ++代码 [已编辑的工作版本]

#include <stdio.h>
#include <Windows.h>
#include <iostream>

int main()
{
int i = 0;

for(;;)
{
    Sleep(1000);
    i++;
    // this version of printf with fflush will work
    printf("The current value of i is %d\n", i);
    fflush(stdout);

    // this version of cout will also work
    //std::cout << "the current value of i is " << i << std::endl;
}

printf("Program exit\n");
}

1 个答案:

答案 0 :(得分:0)

感谢大家的所有投入!

我想我会将我的所有printf更改为std :: cout和std :: endl以用于我的C ++控制台程序。