Running a c++ console app inside a C# console app

不想你离开。 提交于 2019-12-22 14:55:33

问题


I have a c++ console app which runs in visual studio. This collects data and displays it in the console with all the raw data.

Another app (C#) is used to collect this information and present it to the UI.

Is it possible to combine the two by putting the C++ one inside the C# one so that both run at the same time as one service with the C++ app outputting its info to a panel or anything similar?

Thanks! :)


回答1:


A very quick example I have to do something like I said earlier is this:

private void executeCommand(string programFilePath, string commandLineArgs, string workingDirectory)
    {
        Process myProcess = new Process();

        myProcess.StartInfo.WorkingDirectory = workingDirectory;
        myProcess.StartInfo.FileName = programFilePath;
        myProcess.StartInfo.Arguments = commandLineArgs;
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.StartInfo.RedirectStandardOutput = true;
        myProcess.StartInfo.RedirectStandardError = true;
        myProcess.Start();

        StreamReader sOut = myProcess.StandardOutput;
        StreamReader sErr = myProcess.StandardError;

        try
        {
            string str;

            // reading errors and output async...

            while ((str = sOut.ReadLine()) != null && !sOut.EndOfStream)
            {   
              logMessage(str + Environment.NewLine, true);
              Application.DoEvents();
              sOut.BaseStream.Flush();
            }

            while ((str = sErr.ReadLine()) != null && !sErr.EndOfStream)
            {
              logError(str + Environment.NewLine, true);
              Application.DoEvents();
              sErr.BaseStream.Flush();
            }

            myProcess.WaitForExit();
        }
        finally
        {
            sOut.Close();
            sErr.Close();
        }
    }

surely it's not perfect but it worked when executing a powershell script, I was seeing the output in a multiline textbox updating whenever something new came out, the method which updated my textbox was the logMessage()




回答2:


As I understand it, you could run the c++ application from your C# application, you start it in another process and you redirect the standard output of that process so you are able to consume it in the way you want, like for example you can put it in a panel.




回答3:


Sounds like you need to read from the stdout of the console application from the UI application. This article shows how this type of thing is done in C (on Windows). I'm sure with a bit of research you'll find how to do it in C# (as it's an operating system feature, not a language feature).



来源:https://stackoverflow.com/questions/4947043/running-a-c-console-app-inside-a-c-sharp-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!