2011-01-26 115 views
3

我已經編寫了一個C++程序(它從命令行執行),工作正常。現在我需要將它用於我的C#應用​​程序。也就是說,我希望我的C++程序的輸出在我的C#應用​​程序中被使用。在C#應用程序中使用命令行程序

可能嗎?如果是這樣,怎麼樣?

任何鏈接或幫助,將不勝感激。

回答

8

您可以使用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; 
1

製作您的C++代碼DLL,並使用pinvoke從C#代碼調用C++函數。

閱讀這篇文章:Calling Win32 DLLs in C# with P/Invoke

另一種方式做,這是使用Process類從.NET。使用Process,您不需要製作C++代碼DLL;你可以從C#代碼開始你的C++ EXE。

1

你可以有你的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

0

因爲它似乎OP沒有留下任何進一步的評論,我只是想知道,會| |沒有足夠的?我想它歸結爲「」中的「它」的對象,只要它被稱爲「。如果「it」指的是C++程序,那麼Andy Mikula的答案是最好的。如果「它」是指C#程序,那麼我會建議:

C:\>myCpluplus.exe | myCsharp.exe 

並簡單地從Console.In內讀取myCsharp.exe。