虚幻5启动外部进程并获取所有输出的方法

 1 int LaunchExternalProcess(const FString& InExecutablePath, const FString& InCommandArgument)
 2 {
 3     const bool bLaunchDetached = false;
 4     const bool bLaunchHidden = true;
 5     const bool bLaunchReallyHidden = true;
 6 
 7     int ReturnCode = 0;
 8     void* PipeRead = nullptr;
 9     void* PipeWrite = nullptr;
10 
11     verify(FPlatformProcess::CreatePipe(PipeRead, PipeWrite));
12 
13     FProcHandle ProcessHandle = FPlatformProcess::CreateProc(
14         *InExecutablePath, 
15         *InCommandArgument, 
16         bLaunchDetached, 
17         bLaunchHidden, 
18         bLaunchReallyHidden, 
19         nullptr, 
20         0, 
21         nullptr, 
22         PipeWrite, 
23         nullptr, 
24         nullptr
25     );
26 
27     if (ProcessHandle.IsValid())
28     {
29         TArray<uint8> BinaryFileContent;
30         while (FPlatformProcess::IsProcRunning(ProcessHandle))
31         {
32             FPlatformProcess::Sleep(0.01);
33 
34             TArray<uint8> BinaryData;
35             FPlatformProcess::ReadPipeToArray(PipeRead, BinaryData);
36             if (BinaryData.Num() > 0)
37             {
38                 BinaryFileContent.Append(MoveTemp(BinaryData));
39             }
40         }
41 
42         TArray<uint8> BinaryData;
43         FPlatformProcess::ReadPipeToArray(PipeRead, BinaryData);
44         if (BinaryData.Num() > 0)
45         {
46             BinaryFileContent.Append(MoveTemp(BinaryData));
47         }
48 
49         FPlatformProcess::GetProcReturnCode(ProcessHandle, &ReturnCode);
50         
51         FPlatformProcess::CloseProc(ProcessHandle);
52 
53         BinaryFileContent.Add(0);
54 
55         if (ReturnCode == 0)
56         {
57             UE_LOG(LogTemp, Log, TEXT("%s"), ANSI_TO_TCHAR((char*)BinaryFileContent.GetData()));
58         }
59         else
60         {
61             UE_LOG(LogTemp, Error, TEXT("exit code: %d\n%s"), ReturnCode, ANSI_TO_TCHAR((char*)BinaryFileContent.GetData()));
62         }        
63 
64         FPlatformProcess::ClosePipe(PipeRead, PipeWrite);
65 
66         return ReturnCode;
67     }
68     else
69     {
70         UE_LOG(LogTemp, Error, TEXT("Failed to launch %s"), *InExecutablePath);
71 
72         FPlatformProcess::ClosePipe(PipeRead, PipeWrite);
73     }
74 
75     return -1;
76 }

       可以用于启动外部工具执行外部操作。

posted @ 2023-11-13 14:34  bodong  阅读(63)  评论(0编辑  收藏  举报