在C#应用程序中使用命令行程序
我已经编写了一个C++程序(它从命令行执行),工作正常。现在我需要将它用于我的C#应用程序。也就是说,我希望我的C++程序的输出在我的C#应用程序中被使用。在C#应用程序中使用命令行程序
可能吗?如果是这样,怎么样?
任何链接或帮助,将不胜感激。
您可以使用System.Diagnostics.Process
来启动您的C++程序并将其输出重定向到您的C#应用程序中使用的流。在this question的信息详细的细节:
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++函数。
阅读这篇文章:Calling Win32 DLLs in C# with P/Invoke
另一种方式做,这是使用Process类从.NET。使用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没有留下任何进一步的评论,我只是想知道,会| |没有足够的?我想它归结为“”中的“它”的对象,只要它被称为“。如果“it”指的是C++程序,那么Andy Mikula的答案是最好的。如果“它”是指C#程序,那么我会建议:
C:\>myCpluplus.exe | myCsharp.exe
并简单地从Console.In内读取myCsharp.exe。