![](/img/trans.png)
[英]Set UTF-8 Input and Get UTF-8 Output through pipe to/from Powershell with C/C++
[英]C++ Getting UTF-8 output from CreateProcess()
我無法使它工作,所以我從CreateProcess()
獲得UTF-8輸出到wstring
。
目前我正在運行此方法來執行此操作但沒有UTF-8輸出:
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hChildStd_ERR_Rd = NULL;
HANDLE g_hChildStd_ERR_Wr = NULL;
PROCESS_INFORMATION CreateChildProcess(void);
void ReadFromPipe(PROCESS_INFORMATION);
string run(char *command){
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if ( ! CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &sa, 0) ) {
exit(1);
}
if ( ! SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0) ){
exit(1);
}
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0) ) {
exit(1);
}
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ){
exit(1);
}
char *szCmdline=command;
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
bool bSuccess = FALSE;
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_ERR_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NO_WINDOW, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
CloseHandle(g_hChildStd_ERR_Wr);
CloseHandle(g_hChildStd_OUT_Wr);
if ( ! bSuccess ) {
exit(1);
}
DWORD dwRead;
CHAR chBuf[BUFSIZE];
bool bSuccess2 = FALSE;
std::string out = "", err = "";
for (;;) {
bSuccess2=ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess2 || dwRead == 0 ) break;
std::string s(chBuf, dwRead);
out += s;
}
dwRead = 0;
for (;;) {
bSuccess2=ReadFile( g_hChildStd_ERR_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess2 || dwRead == 0 ) break;
std::string s(chBuf, dwRead);
err += s;
}
return out;
}
我嘗試了幾件事,但沒有成功使它工作。
任何幫助表示贊賞!
命令的輸出是字節流。 所以你把它作為字節流來讀。 由兩個程序決定使用的編碼。
例如:
如果您執行.NET(C#/ VB.NET)控制台應用程序,則應用程序可以使用Console.OutputEncoding
來設置Console.Write[Line]
方法將使用的編碼。
Console.OutputEncoding = Text.Encoding.UTF8;
同樣,PowerShell腳本可以使用[Console]::OutputEncoding
來設置Write-Output
或Write-Host
cmdlet將使用的編碼。
[Console]::OutputEncoding = [Text.Encoding]::UTF8
cmd.exe
或批處理文件可以使用chcp
命令 。
chcp 65001
如果使用WriteConsole
,Win32應用程序可以使用SetConsoleOutputCP
函數來設置其輸出編碼。 如果應用程序正在使用WriteFile
, WriteFile
需要編寫已按需要編碼的字節(例如,使用WideCharToMultiByte
)。
SetConsoleOutputCP(CP_UTF8);
然后,當您讀取應用程序輸出時,使用約定的編碼對字節流進行解碼。 例如,使用MultiByteToWideChar
函數 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.