首页 > 解决方案 > 从 C# 使用参数在 C++ 上运行 .exe

问题描述

我在 C++ 上有一个应用程序,在 C# 上有一个应用程序(用于 GUI)。

我在新进程中从 C# 运行 exe - 文件 (C++) 并将参数传递给命令行。

代码 C#:

System.Diagnostics.Process Proc = new System.Diagnostics.Process();
Proc.StartInfo.FileName = "main.exe";
Proc.StartInfo.Arguments = "p";
Proc.Start();

代码 C++:

if (char(argv[1]) == 'p') 
     {
            program.SetUniform("cur_color", make_float3(0.5f, 0.5f, 0.0f));
            std::cout << "This is true" << std::endl;
     }
else {
            std::cout << "This is false    " << argv[1] << std::endl;
            program.SetUniform("cur_color", make_float3(0.9f, 0.9f, 0.9f));
     }

但结果我得到了“这是错误的 p”。

我不知道为什么。你能帮助我吗?传递的参数类型可能有问题吗?谢谢!

标签: c#c++

解决方案


您不能以这种方式进行比较,因为 C++ 中的参数是作为char**whereargv[0] argv[1]等传递的,是由空格分隔的参数创建的数组。

例子:

main.exe foo bar

argv[0] == ['f','o','o']
argv[1] == ['b','a','r']

文档:这里

所以你需要遍历字符进行比较或std::vector<std:string>argv

例子:

C# Program Calling C++ Exe
  main.exe p foo bar
C++ Program Getting Parameters and comparing them
  argv[1][0] == 'p'

比较简单的方法,但在非复杂解决方案中并不快:

std::vector<std::string> vectorOfArguments(argv + 1, argv + argc);

然后你可以浏览矢量

for(auto & argument : vectorOfArguments){
   //Some Action
}

希望它有所帮助


推荐阅读