[英]Using a command line program from within a C# application
我编写了一个C ++程序(从命令行执行),工作正常。 现在我需要将它用于我的C#应用程序。 也就是说,我希望我的C ++程序的输出可以在我的C#应用程序中使用。
可能吗? 如果是这样,怎么样?
任何链接或帮助将不胜感激。
您可以使用System.Diagnostics.Process
启动C ++程序并将其输出重定向到流以在C#应用程序中使用。 此问题中的信息详细说明了具体内容:
string command = "arg1 arg2 arg3"; // command line args
string exec = "filename.exe"; // executable name
string retMessage = String.Empty;
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = exec;
p.StartInfo = startInfo;
p.Start();
using (StreamReader output = p.StandardOutput)
{
retMessage = output.ReadToEnd();
}
p.WaitForExit();
return retMessage;
制作C ++代码DLL,并使用pinvoke从C#代码调用C ++函数。
阅读本文: 使用P / Invoke在C#中调用Win32 DLL
另一种方法是使用.Net的Process类。 使用Process,您不需要制作C ++代码DLL; 你可以从C#代码开始你的C ++ EXE进程。
您可以让您的C ++程序将其输出写入文件,并从文件中读取您的C#程序。
如果您的应用程序对性能非常敏感,那么这不是最好的方法。
以下是运行C ++程序的C#代码:
try
{
Process p = StartProcess(ExecutableFileName);
p.Start();
p.WaitForExit();
}
catch
{
Log("The program failed to execute.");
}
现在您可以从C ++程序写入文件,并在C#程序中读取它。
这将向您展示如何从C ++程序写入文件: http : //www.cplusplus.com/doc/tutorial/files/
这将向您展示如何从C#程序中的文件中读取: http : //msdn.microsoft.com/en-us/library/ezwyzy7b.aspx
由于OP似乎没有留下任何进一步的评论,我想知道,将| 没有足够的? 我想它归结为“ 无论何时被调用 ”中的“它”对象。 如果“它”指的是C ++程序,那么Andy Mikula的答案是最好的。 如果“它”指的是C#程序,那么我会建议:
C:\>myCpluplus.exe | myCsharp.exe
并简单地从myCsharp.exe中的Console.In读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.