重定向printf C++;控制台输出到C#
这是我的方法,当我点击我的C#GUI程序中的一个按钮时会调用它。它启动了一个非常简单的C++控制台程序,它只在一个无终止循环中每秒打印出一行。重定向printf C++;控制台输出到C#,c#,c++,redirect,C#,C++,Redirect,这是我的方法,当我点击我的C#GUI程序中的一个按钮时会调用它。它启动了一个非常简单的C++控制台程序,它只在一个无终止循环中每秒打印出一行。 private static Process process; private void LaunchCommandLineApp() { process = new Process(); process.StartInfo.FileName = "SimpleTest.exe"; process.StartInfo.UseSh
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来显示这些语句
FY:我的C++代码<强> [编辑工作版本] < /St>>:
#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");
}
#包括
#包括
#包括
int main()
{
int i=0;
对于(;;)
{
睡眠(1000);
i++;
//此版本的printf和fflush将起作用
printf(“i的当前值为%d\n”,i);
fflush(stdout);
//这个版本的cout也可以使用
//std::cout感谢各位的投入
<>我想我会把所有的打印文件都改成STD::CUT和STD::Endl,用于C++控制台程序。你是否允许C++程序运行足够长,以便<代码> STDUD/<代码>的内部缓冲区填充和刷新?我不知道默认的缓冲区大小是多少,它可能是4K左右。如果这个问题的答案是“否”还是“嗯?”,尝试缩短睡眠时间,延长消息时间,运行程序至少几秒钟,然后查看C#程序是否在一段时间后突然同时看到大量输出。是否确定process.StartInfo.RedirectStandardOutput=false;?如果是,则您的问题是写入stdout
的数据会被缓冲;您是应该能够使其具有行缓冲(即,输出实际上会在每一行换行时写入)但是我认为Microsoft C运行时不支持这一点;但是您可以通过调用setvbuf
:或者您可以编写到stderr
而不是stdout
;stderr
是无缓冲的。您能显示一下您在std::cout
中使用的行吗?您使用的std::endl
not不仅添加换行符,还刷新输出。要使其在C程序中工作,必须在printf
之后执行fflush(stdout);
。