[英]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.