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:
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.
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);