vc 调用exe并传入参数得到返回值
时间: 2023-10-28 14:03:35 浏览: 108
执行外部exe获取返回值
VC(Visual C++)可以通过调用外部的.exe文件并传入参数,然后获取该程序的返回值。以下是一个简单的示例代码:
```cpp
#include <windows.h>
#include <iostream>
int main()
{
std::string programPath = "C:\\path\\to\\program.exe";
std::string parameters = "param1 param2 param3";
// 创建一个匿名管道,用于接收程序的输出
HANDLE hReadPipe, hWritePipe;
SECURITY_ATTRIBUTES securityAttributes;
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.bInheritHandle = TRUE;
securityAttributes.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hReadPipe, &hWritePipe, &securityAttributes, 0))
{
std::cerr << "无法创建管道!" << std::endl;
return -1;
}
// 启动程序并将输出重定向到管道
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory(&startupInfo, sizeof(startupInfo));
ZeroMemory(&processInformation, sizeof(processInformation));
startupInfo.cb = sizeof(startupInfo);
startupInfo.hStdInput = NULL;
startupInfo.hStdOutput = hWritePipe;
startupInfo.hStdError = hWritePipe;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
if (!CreateProcess(NULL, const_cast<LPSTR>(programPath.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInformation))
{
std::cerr << "无法启动程序!" << std::endl;
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
return -1;
}
// 等待程序结束并获取返回值
WaitForSingleObject(processInformation.hProcess, INFINITE);
DWORD exitCode;
GetExitCodeProcess(processInformation.hProcess, &exitCode);
// 读取程序输出
char buffer[1024];
DWORD bytesRead;
std::string output;
while (ReadFile(hReadPipe, buffer, sizeof(buffer), &bytesRead, NULL) && bytesRead > 0)
{
output.append(buffer, bytesRead);
}
// 关闭句柄
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(processInformation.hProcess);
CloseHandle(processInformation.hThread);
std::cout << "程序返回值:" << exitCode << std::endl;
std::cout << "程序输出:" << std::endl;
std::cout << output << std::endl;
return 0;
}
```
上述代码首先使用`CreatePipe`函数创建了一个匿名管道,然后使用`CreateProcess`函数启动目标程序,并将其标准输出重定向到管道。接下来,使用`WaitForSingleObject`函数等待程序结束,并通过`GetExitCodeProcess`函数获得程序的返回值。最后,使用`ReadFile`函数读取管道中的输出,并关闭相关的句柄。
这样,我们就可以通过VC调用外部的.exe文件并传入参数,并获取到该程序的返回值。
阅读全文