# 用 C++ 呼叫 C# Console Mod 環境 VS 2015 ## 建立 C# 專案 ![](https://i.imgur.com/M0gVWVu.png) ![](https://i.imgur.com/47ruiU0.png) ### 主要函式 ```c# static void Main( string [] args ) ``` 接下來就能寫程式了 #### 範例 ```c# static void Main( string [] args ) { if ( args.Length == 0 ) { Console.WriteLine("No args"); } else { Console.WriteLine("You have " + args.Length + " args"); for ( int i = 0; i < args.Length; i++ ) { Console.WriteLine( (i+1) + ". " + args[i]); } } } ``` * string [] args 是參數 * 參數就是使用命令列呼叫程式時添加在後面的字串 * 參數是字串依照空白分割的動態陣列, 寫完之後要測試就先建置,建置之後打開專案資料夾與 PowerShell * PowerShell 打開方式 Win+R ![](https://i.imgur.com/wjEyToI.png) 或 Win+X ![](https://i.imgur.com/XIFxBSr.png) ![](https://i.imgur.com/QLoqMrx.png) 在專案資料夾找到 .exe 檔 ![](https://i.imgur.com/wmMAf1y.png) 可以直接拖曳到 PowerShell 視窗 ![](https://i.imgur.com/zLNgVRM.png) Enter 執行 ![](https://i.imgur.com/lo46uwP.png) 這樣就能做相關的功能了 ## C++ 呼叫 C# Console Mode 我做的功能 C++ 呼叫程式並附上路徑 ```c++ QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("Unable to open file"),file.errorString()); return; } // 記得把 C# 程式放在同資料夾 string str = "Console_toDXF.exe "+fileName.toStdString();// fileName; char *command = new char[999]; // 把 String 轉成 Char strcpy(command, str.c_str()); system(command); ```` * system(command) * 相當於 PowerShell 的輸入視窗 * 也就是說 PowerShell 輸入 ![](https://i.imgur.com/vikpN5l.png) * 就等於 system("ConsoleApplication1.exe a b c d") * 注意路徑的變化,最好傳路徑都傳絕對路徑 C# 負責接收座標檔的路徑並在同一位置輸出 Dxf 檔 ```C# static void Main( string [] args ) { // 設定檔案路徑 if ( args.Length != 0 ) { string filePath = args [0]; List<string> Coords = new List<string>(); // 讀取檔案 try { StreamReader readCrd = new StreamReader(filePath ); string XYcoord; while ( ( XYcoord = readCrd.ReadLine() ) != null ) { //開始一行一行讀取囉!! Coords.Add(XYcoord.ToString()); } //讀完檔案存檔 try { saveFile(Coords,filePath); Console.WriteLine(filePath + " trans to DXF file done!!"); } catch ( Exception ) { Console.WriteLine("Something Wrong , check Code"); throw; } } catch ( Exception ) { Console.WriteLine("Path or File Name ERROR!!"); throw; } } else { Console.WriteLine("No argument!!"); } } ```