C++或C#调用外部exe的分析

假如有个外部程序名为A.exe,放在目录E:\temp\下,然后我们用C++或者C#写一个程序调用这个A.exe的话(假设这个调用者所在的路径在D:\invoke),通常会采用下面的代码:

// C# code

string exeName = @"E:\temp\A.exe";
Process g = new Process();
g.StartInfo.UseShellExecute = false;
g.StartInfo.RedirectStandardOutput = false;
g.StartInfo.FileName = exeName;
g.StartInfo.CreateNoWindow = false;
g.StartInfo.Arguments = "-R";          // Supposing there is a "-R" parameter
g.Start();
g.WaitForExit();
// C++ code

SHELLEXECUTEINFO  ShExecInfo  =  {0}; 
ShExecInfo.cbSize        =  sizeof(SHELLEXECUTEINFO); 
ShExecInfo.fMask        =  SEE_MASK_NOCLOSEPROCESS; 
ShExecInfo.hwnd        =  NULL; 
ShExecInfo.lpVerb        =  TEXT("open"); 
ShExecInfo.lpFile        =  TEXT("E:\\temp\\A.exe"); 
ShExecInfo.lpParameters     =  TEXT("-R");
ShExecInfo.nShow        =  SW_HIDE; 
ShExecInfo.hInstApp        =  NULL;   
ShellExecuteEx(&ShExecInfo);
WaitCursorBegin();
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);

但是当我们的A.exe程序中使用相对路径创建或者打开文件时,就会发现用上面程序调用A.exe时,会提示无法创建文件或者无法打开文件,其原因是:

  1. A.exe的调用者和A.exe不在同一个目录下;
  2. 当异地调用A.exe时,A.exe程序里的相对路径都是相对于其调用者所在的目录而言(都是相对于D:\invoke)

解决办法很简单:

  1. C#代码中,加入g.StartInfo.WorkingDirectory = @"E:\temp";
  2. C++代码中,加入ShExecInfo.lpDirectory  =  TEXT("E:\\temp\\");
  3. 上面两行代码的作用是指定A.exe运行的目录,这样就保证了A.exe里面使用的相对于路径是相对于A.exe所在的目录,即E:\temp
posted @ 2017-07-18 15:06  朝雾之归乡  阅读(3114)  评论(0编辑  收藏  举报