【问题标题】:Running a c++ console app inside a C# console app在 C# 控制台应用程序中运行 C++ 控制台应用程序
【发布时间】:2011-02-09 15:40:03
【问题描述】:

我有一个在 Visual Studio 中运行的 c++ 控制台应用程序。这会收集数据并将其与所有原始数据一起显示在控制台中。

另一个应用程序 (C#) 用于收集此信息并将其呈现给 UI。

是否可以通过将 C++ 之一放在 C# 之一中来将两者结合起来,以便两者作为一项服务同时运行,而 C++ 应用程序将其信息输出到面板或类似的东西?

谢谢! :)

【问题讨论】:

  • 它是托管的 C++ 吗?你可以直接使用它。如果它不是托管的,您可以使用Process 类来启动一个进程(控制台应用程序)。

标签: c# c++ service console-application


【解决方案1】:

我必须像前面所说的那样做一个非常简单的例子是:

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();
        }
    }

当然它并不完美,但它在执行 powershell 脚本时有效,每当有新内容出现时,我看到多行文本框中的输出会更新,更新我的文本框的方法是 logMessage()

【讨论】:

  • 感谢提交。我给你投了赞成票!此代码中的 Process 和 StreamReader 函数需要哪些 using 指令?
  • 如果我想要 2 个 commandLineArgs,我只是列出 myProcess.StartInfo.Arguments = commandLineArgs 2x 还是允许在其下放置 2 行?在这种情况下 StartInfo 是什么?谢谢!
【解决方案2】:

据我了解,您可以从 C# 应用程序运行 c++ 应用程序,在另一个进程中启动它,然后重定向该进程的标准输出,以便您能够以您想要的方式使用它,例如你可以把它放在一个面板中。

【讨论】:

    【解决方案3】:

    听起来您需要从 UI 应用程序中读取控制台应用程序的 stdoutThis 文章展示了这种类型的事情是如何在 C 中完成的(在 Windows 上)。我相信通过一些研究,您会发现如何在 C# 中执行此操作(因为它是操作系统功能,而不是语言功能)。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2011-01-22
      • 2010-10-16
      • 2013-06-10
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2021-11-14
      • 2011-08-16
      相关资源
      最近更新 更多