英文:
[SOLVED]create a child process with STDIN and STDOUT as being piped in UTF-16
问题
以下是您要翻译的内容:
我使用CreateProcessW
函数创建了一个子进程,该子进程之间与其父进程之间有作为STDOUT和STDIN的管道。我无法使用WriteFile
和ReadFile
函数以宽字符的方式发送和接收数据。
我不知道如何为管道设置std::locale。是否有一种特定的方法可以告诉这些管道将数据编码为UTF-16的宽字符,类似于我们在ifstreams和ofstreams中使用的方式?
谢谢。
这是您要的翻译内容。
英文:
I have created a child process with the use of CreateProcessW
function which has pipes to be as the STDOUT and STDIN between itself and its parent process. I am not able to use WriteFile
and ReadFile
functions to send and get back data as wide characters.
I am not aware of setting std::locale for pipes. Is there a way to specifically tell those pipes to encode data as wide characters in UTF-16, similar to what one uses for ifstreams and ofstreams?
Thanks.
Here you are:
const unsigned int sz = 1024;
static wchar_t buffer [sz];
int WriteToPipe(const std::wstring& str)
{
int result = WriteFile(PipeStdin, (LPVOID)str.c_str(), str.size(), &bytesWritten, NULL);
_assert(str.size()==bytesWritten);
return result;
}
// simply turns back what was on its stdin
wchar_t* ReadFromPipe()
{
ReadFile(PipeStdout, (LPVOID)buffer, sz, &bytesRead, NULL);
return buffer;
}
void Test()
{
std::wstring test { L"test" };
WriteToPipe (test);
wchar_t* ret = ReadFromPipe (); // gets back 't' when using std::wcout
}
It gets only 't', apparently because the buffer was t \0 e \0 s \0 t \0.
If pipe's default encoding is UTF-8, it makes sense, otherwise I have to find out what is doing there. If I could set pipes to treat the buffer as UTF-16, then it would be good.
答案1
得分: 2
WriteFile接受要写入的字节数,而不是字符数。
当我用sizeof (wchar_t) * str.size ()
替换str.size ()
时,整个字符串都被写入并读取出来。至少当我使用默认参数调用CreatePipe创建管道时。
还要确保在传递给wprint或wout之前对其进行NUL终止。
英文:
WriteFile takes number of bytes to write, not number of characters.
When I replace str.size ()
there with sizeof (wchar_t) * str.size ()
then the whole string gets written and then read out. At least when I create the pipe with plain CreatePipe call with default parameters.
Also be sure to NUL-terminate it before passing to wprint or wout.
答案2
得分: 0
I made two changes in my 'Preprocessor Definitions,' namely adding _UNICODE and _MBCS macros available, and also adding UTF-16 mode for std::wcin as follows:
const unsigned long MaxCode = 0x10FFFF;
const std::codecvt_mode Mode = (std::codecvt_mode)(std::generate_header | std::little_endian);
std::locale utf16_locale(std::wcin.getloc(), new std::codecvt_utf16<wchar_t, MaxCode, Mode>);
std::wcin.imbue(utf16_locale);
英文:
Solution:
I made two changes in my 'Preprocessor Defenitions' namely adding _UNICODE and _MBCS macros available and also adding UTF-16 mode for std::wcin as follows:
const unsigned long MaxCode = 0x10FFFF;
const std::codecvt_mode Mode = (std::codecvt_mode)(std::generate_header | std::little_endian);
std::locale utf16_locale(std::wcin.getloc(), new std::codecvt_utf16<wchar_t, MaxCode, Mode>);
std::wcin.imbue (utf16_locale);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论