这里包含两个问题。第一个首先是如何让exe具有接收参数的能力。
对于一个C/C++编写的程序,通过对main函数的定义可以让exe文件具有接收参数的能力:
int main(int argc,char* argv[])//也可以写成char** argv
{
int i;
for (i = 0; i < argc; i++)
printf("Argument %d is %s.\n", i, argv[i]);
while (1);
return 0;
}
显然这里面的argc是参数的数目,是程序自行计算的,argv[i]则依次是字符串形式的参数。
然后用Unity,也就是C#去启动这个exe。
using System.Diagnostics;
void StartEXE()
{
ProcessStartInfo StartProcess = new ProcessStartInfo();
StartProcess.FileName = "E:/学习/五院项目/ConsoleTest/Debug/ConsoleTest.exe";
StartProcess.Arguments = "启动 1 2 3 哈哈哈";
Process.Start(StartProcess);
}
在Unity中传入了5个参数,但EXE总共读入了6个参数,其中第一个参数是EXE文件的路径。
如果要用C#写EXE,写法稍微有所不同。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpTest
{
class Program
{
static void Main(string[] args)
{
int i;
Console.WriteLine("共有" + args.Length + "个参数:");
for (i=0;i<args.Length;i++)
{
Console.WriteLine("参数" + i + ":" + args[i]);
}
while (true) ;
}
}
}
直接用一个字符串数组来代表所有的参数,而args.Length则代表了参数的个数(实际上就是数组元素的个数)。同样用上面的方法去调用这个exe,得到的结果和C++编写的也稍微有点不一样:
从这里可以看出来我们传入多少个参数,程序就是多少个参数,没有自带的那个路径。